I am using asp.net web-form and gridview on several pages to display data. I bind gridview from codebehind file.
SO far i am able to use following code to bind datasource to gridview and also enable paging but i a facing problem to enable sorting on the same grid. Any point or help regarding how to enable paging to make it work with the below code.
I also have addition fields which are not part of this code which i use for additional functionality
onrowdatabound="GridView1_RowDataBound" onrowcommand="GridView1_RowCommand"
.ASPX File
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="ID"
Width="990px" BackColor="White" BorderColor="WhiteSmoke" BorderStyle="None" BorderWidth="0px" CellPadding="5"
Font-Names="Verdana" Font-Size="X-Small" ForeColor="Black" GridLines="Horizontal" PageSize="10" CssClass="myheader" AllowSorting="true"
onrowdatabound="GridView1_RowDataBound" onrowcommand="GridView1_RowCommand" onpageindexchanging="GridView1_PageIndexChanging" >
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />
<asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName" />
<asp:BoundField DataField="Date" HeaderText="Date" SortExpression="Date" DataFormatString="{0:yyyy/MM/dd}"/>
</Columns>
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<HeaderStyle Height="32px" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" BorderStyle="None" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#4B4B4B" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#242121" />
<RowStyle BorderColor="#f5f5f5" BorderStyle="Notset"/>
</asp:GridView>
CODE BEHIND
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetDetails();
}
}
protected void GetDetails()
{
string strSql = "SELECT * FROM Test_Table Order by Date Desc ";
DataSet ds = DataProvider.Connect_Select(strSql);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GetDetails();
}
UPDATE: Code updated to
.ASPX
OnSorting="GridView1_OnSorting"
CODE BEHIND
protected void GridView1_OnSorting(object sender, GridViewSortEventArgs e)
{
string strSql = "SELECT * FROM Test_Table ";
DataSet ds = DataProvider.Connect_Select(strSql);
DataTable dataTable = ds.Tables[0];
DataTable dataTable = ds.Tables[0];
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " "+e.SortDirection;
GridView1.DataSource = dataView;
GridView1.DataBind();
}
}
Best Answer
You should create sorting event like this :
Also you can take sort direction in view state on page
I hope above code help you.