i have an asp:GridView
control, which i've set the AllowSorting="True"
property on:
<asp:GridView ID="gridUsers" runat="server" PageSize="100" ShowHeaderWhenEmpty="True"
Width="100%" AllowSorting="True" onrowcreated="gridUsers_RowCreated"
onsorting="gridUsers_Sorting">
</asp:GridView>
At design time the grid looks sortable:
But at runtime only the middle column is sortable:
How do i make an asp:GridView
sortable in ASP.NET?
Note: The asp:GridView
with AllowSorting
requires a Sorting
event handler to be present:
protected void gridUsers_Sorting(object sender, GridViewSortEventArgs e)
{
//asp:GridView will throw an exception if a Sorting event handler isn't present
}
Update: i realized what's special about the Description column. It's the only column whose display name is correct from the database as-is. The remaining columns i have to fix the display name to be presentable:
protected void gridUsers_RowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Visible = false; //UserGUID
e.Row.Cells[1].Text = "User name";
e.Row.Cells[2].Text = "Full name";
//3=Description
e.Row.Cells[4].Text = "E-mail";
e.Row.Cells[5].Text = "Active";
e.Row.Cells[5].Visible = false;
e.Row.Cells[6].Text = "Account type";
}
Now i just have to figure out the tricky part; and make columns sortable.
this code will definitely help you:
In the GridView, Make the Property AllowSorting = "True" and in the GridView Columns give like this
<asp:BoundField DataField="UserName" HeaderText="User Name" SortExpression="UserName" />
<asp:BoundField DataField="FullName" HeaderText="Full Name" SortExpression="FullName" />
and also use the below coding:
protected void gv_Sorting(object sender, GridViewSortEventArgs e)
{
try
{
string sortExpression = e.SortExpression;
ViewState["z_sortexpresion"] = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, "DESC");
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, "ASC");
}
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["sortDirection"];
}
set
{
ViewState["sortDirection"] = value;
}
}
private void SortGridView(string sortExpression, string direction)
{
DTSorting = new DataView(DTSorting, "", sortExpression + " " + direction, DataViewRowState.CurrentRows).ToTable();
gv.DataSource = DTSorting;
gv.DataBind();
}
public DataTable DTSorting
{
get
{
if (ViewState["Sorting"] != null)
{
return (DataTable)ViewState["Sorting"];
}
else
return null;
}
set
{
ViewState["Sorting"] = value;
}
}
Here, Consider "DTSorting" is the DataTable by which you binds the GridView "gv".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With