How can I sort data wh-ich is in a datagrid view.
The language I am using is C sharp language.
Regards.
Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Khargesh RajputRank #616 · 3.9K reputationPosted Apr 24, 2015, 7:48 PM EDT
then in your query use
order by clause
Venkat KumarRank #3,138 · 456 reputationPosted Apr 24, 2015, 10:23 PM EDT
sort.aspx.cs
public partial class sort : System.Web.UI.Page
{
string conn = ConfigurationManager.ConnectionStrings["con"].ToString();
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
public void BindData()
{
SqlConnection connec = new SqlConnection();
connec.ConnectionString = conn;
connec.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connec;
cmd.CommandText = "select * from tbldept";
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
gv.DataSource = ds;
gv.DataBind();
connec.Close();
}
public SortDirection dir
{
get
{
if (ViewState["dirState"] == null)
{
ViewState["dirState"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["dirState"];
}
set
{
ViewState["dirState"] = value;
}
}
protected void gv_Sorting(object sender, GridViewSortEventArgs e)
{
BindData();
DataTable dt = new DataTable();
dt = ds.Tables[0];
{
string SortDir = string.Empty;
if (dir == SortDirection.Ascending)
{
dir = SortDirection.Descending;
SortDir = "Desc";
}
else
{
dir = SortDirection.Ascending;
SortDir = "Asc";
}
DataView sortedView = new DataView(dt);
sortedView.Sort = e.SortExpression + " " + SortDir;
gv.DataSource = sortedView;
gv.DataBind();
}
}
}
sort.aspx