Sorting in GridView + Asp.net - c#

What should I do to perform the sorting in grid view?
Please help

You can implement code like the following:
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = GridView1.DataSource as DataTable;
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
GridView1.DataSource = dataView;
GridView1.DataBind();
}
}
private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;
case SortDirection.Descending:
newSortDirection = "DESC";
break;
}
return newSortDirection;
}
With this code, your GridView definition should read:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowSorting="true" OnSorting="GridView1_Sorting">
<Columns>
<asp:BoundField DataField="Name" HeaderText="People Names" SortExpression="Name" />
<asp:BoundField DataField="Age" HeaderText="People Ages" SortExpression="Age" />
</Columns>
</asp:GridView>

Not sure if you have already added the event or not in your code behind.
You have AllowSorting="true" set for the GridView and therefore you need to
have event handler for its Sorting event.
< asp:GridView AllowSorting=true ID="GridView1" runat="server"
OnSorting="GridView1_Sorting" >
...
< /asp:GridView >
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//Add your code here for handling
}

Related

Sorting is lost when i move to next page of GridView in asp.net webform C#

I have a simple gridview to display records, and i am using sorting to sort by all columns. When am on first page, sorting works by when i move to next page then it shows me un sorted records again.
<asp:GridView ID="gv" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="ID"
Width="1100px" BackColor="White" BorderColor="#f5f5f5" BorderStyle="None" BorderWidth="0px" CellPadding="5" Font-Names="Verdana" Font-Size="X-Small" ForeColor="Black" GridLines="Horizontal" PageSize="500" CssClass="myheader" OnPageIndexChanging="gv_PageIndexChanging" OnSorting="gv_Sorting" AllowSorting="true" onrowdatabound="gv_RowDataBound" onrowcommand="gv_RowCommand" >
CODE BEHIND
protected void gv_Sorting(object sender, GridViewSortEventArgs e)
{
// getCareerList();
// DataTable dataTable = gv.DataSource as DataTable;
DataSet ds = new DataSet();
ds = DataProvider.GetFormByFormTypeIDForGridview(int.Parse(ddCareerType.SelectedItem.Value.ToString()));
DataTable dataTable = ds.Tables[0];
string SortDirection = "DESC";
if (ViewState["SortExpression"] != null)
{
if (ViewState["SortExpression"].ToString() == e.SortExpression)
{
ViewState["SortExpression"] = null;
SortDirection = "ASC";
}
else
{
ViewState["SortExpression"] = e.SortExpression;
}
}
else
{
ViewState["SortExpression"] = e.SortExpression;
}
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " + SortDirection;
gv.DataSource = dataView;
gv.DataBind();
}
}
I am not sure what is causing this
I would suggest setting a breakpoint at:
dataView.Sort = e.SortExpression + " " + SortDirection;
and check if the value of SortDirection is as expected. If not there is a issue with storing the order in the ViewState. If not you it is something in the DataView.
May this post help you sorting-is-not-working-on-gridview-in-asp-net

Gridview paging using Datatable - not working

I have a gridview which has paging but when I click on Page 2 - page refreshes and returns the first page and the page link also remains on page 1.
Any help will be really appreciated :)
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
onpageindexchanging="GridView1_PageIndexChanging"
onrowcommand="GridView1_RowCommand" AutoGenerateColumns="False"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="Sequence" HeaderText="Sequence" HeaderStyle-
Width="10%"/>
<asp:TemplateField HeaderStyle-Width="90%">
<ItemTemplate>
<asp:Label ID="lblTitle" runat="server" Text='<%# Eval("Title") %>' Font-
Strikeout='<%# ((Convert.ToBoolean(Eval("Obsolete")))?true:false) %>' />
</ItemTemplate>
</asp:TemplateField>
Codebehind:-
private void BuildResults()
{
DataTable dt01 = obSectionDefinition.List(_criteria.AuditDefinitionGUID,
_criteria.ParentGUID, _criteria.ShowObsolete);
GridView1.PageSize = 20;
ViewState["dt_data"] = dt01;
GridView1.DataSource = dt01;
GridView1.DataBind();
}
PageIndexChanging:-
public void GridView1_PageIndexChanging(object
sender,GridViewPageEventArgse)
{
GridView x = ((GridView)sender);
GridView1.DataSource = ViewState["dt_data"];
if (e.NewPageIndex > -1 && e.NewPageIndex <= x.PageCount)
{
x.PageIndex = e.NewPageIndex+1;
}
else
{
e.NewPageIndex--;
}
GridView1.DataBind();
}
Page Load:-
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BuildResults();
}
}
modify PageIndexChanging code
public void GridView1_PageIndexChanging(object sender,GridViewPageEventArgse)
{
GridView1.DataSource = (DataTable)ViewState["dt_data"];
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
Set AllowPaging=”True” Properties of GridView to enable paging
Set PageSize property to mention how many records will be displayed on
each page.
HTML MARKUP :
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="20"
onpageindexchanging="GridView1_PageIndexChanging"
onrowcommand="GridView1_RowCommand" AutoGenerateColumns="False"
onrowdatabound="GridView1_RowDataBound">
</asp:GridView>
private void BuildResults()
{
DataTable dt01 = obSectionDefinition.List(_criteria.AuditDefinitionGUID, _criteria.ParentGUID, _criteria.ShowObsolete);
// GridView1.PageSize = 20;
// ViewState["dt_data"] = dt01;
GridView1.DataSource = dt01;
GridView1.DataBind();
}
public void GridView1_PageIndexChanging(object sender,GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BuildResults();
}
I had a Response.Write on the page elsewhere and this was causing the paging to fail - removed it and this now works

Gridview sorting when databinding from codebehind file

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();
}
}
You should create sorting event like this :
protected void GridView1_OnSorting(object sender, GridViewSortEventArgs e)
{
//TODO write tour code here to get data from database;
DataTable dataTable = your datatable get from your db;
if (dataTable != null)
{
if (e.SortDirection.ToString() == "Ascending")
{
dataView.Sort = e.SortExpression + " ASC";
}
else if (e.SortDirection.ToString() == "Descending")
{
dataView.Sort = e.SortExpression + " DESC";
}
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " "+e.SortDirection;
GridView1.DataSource = dataView;
GridView1.DataBind();
}
}
**e.SortExpression** provides sorting column name
**e.SortDirection** provides sorting direction like ASC or DESC.
Also you can take sort direction in view state on page
private string GridViewSortDirection
{
get { return ViewState["SortDirection"] as string ?? "DESC"; }
set { ViewState["SortDirection"] = value; }
}
private void SetSortDirection()
{
GridViewSortDirection = (GridViewSortDirection.ToUpper() == "DESC") ? "ASC" : "DESC";
}
I hope above code help you.
SOLUTION
I have deleted the old code it had a bug as sorting was not working properly when one us to move back and forth from one page to another. Below code is test and is working well with sorting & paging.
public partial class _Default : System.Web.UI.Page
{
string Sort_Direction = "Date DESC";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// GetRegistrationDetails();
ViewState["SortExpr"] = Sort_Direction;
DataView dv = Getdata();
GridView1.DataSource = dv;
GridView1.DataBind();
}
}
private DataView Getdata()
{
string strSql = "SELECT * ROM TEST_Table ";
DataSet ds = DataProvider.Connect_Select(strSql);
DataView dv = ds.Tables[0].DefaultView;
dv.Sort = ViewState["SortExpr"].ToString();
return dv;
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
DataView dv = Getdata();
GridView1.DataSource = dv;
GridView1.DataBind();
}
protected void GridView1_OnSorting(object sender, GridViewSortEventArgs e)
{
GridView1.PageIndex = 0;
string[] SortOrder = ViewState["SortExpr"].ToString().Split(' ');
if (SortOrder[0] == e.SortExpression)
{
if (SortOrder[1] == "ASC")
{
ViewState["SortExpr"] = e.SortExpression + " " + "DESC";
}
else
{
ViewState["SortExpr"] = e.SortExpression + " " + "ASC";
}
}
else
{
ViewState["SortExpr"] = e.SortExpression + " " + "ASC";
}
GridView1.DataSource = Getdata();
GridView1.DataBind();
}
}
You have already set AllowSorting="true" and the SortExpression property for each column, so the next step is keeping the last sort expression and sort direction between postbacks, and using them in PageIndexChanging and Sorting event.
I would suggest using ViewState to keep the last sort expression and sort direction
private string SortExpression
{
get
{
return ViewState["SortExpression"] == null ? string.Empty : ViewState["SortExpression"].ToString();
}
set
{
ViewState["SortExpression"] = value;
}
}
private string SortDirection
{
get
{
return ViewState["SortDirection"] == null ? string.Empty : ViewState["SortDirection"].ToString();
}
set
{
ViewState["SortDirection"] = value;
}
}
This is the method to get the next sort direction:
private string GetSortDirection(string sortExpression)
{
if (sortExpression == this.SortExpression)
{
// reverse the sort direction when current sort expression is the same as the last time
if (this.SortDirection == "ASC")
{
return "DESC";
}
else
{
return "ASC";
}
}
else
{
// always return ASC when current sort expression is different than the last time
return "ASC";
}
}
GetDetails method will need to know the sort expression and sort direction, so add sortExpression and sortDirection parameter:
protected void GetDetails(string sortExpression, string sortDirection)
{
string strSql = string.Format("SELECT * FROM Test_Table Order by {0} {1}", sortExpression, sortDirection);
DataSet ds = DataProvider.Connect_Select(strSql);
GridView1.DataSource = ds;
GridView1.DataBind();
// save current sort expression and sort direction to ViewState
this.SortExpression = sortExpression;
this.SortDirection = sortDirection;
}
Make sure you add OnSorting="GridView1_Sorting" to GridView1 markup code:
<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"
OnSorting="GridView1_Sorting" >
Assuming that the default sort expression is Date and the default sort direction is DESC, this is what Page_Load, GridView1_PageIndexChanging, and GridView1_Sorting methods will look like
private const string DEFAULT_SORT_EXPRESSION = "Date";
private const string DEFAULT_SORT_DIRECTION = "DESC";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetDetails(DEFAULT_SORT_EXPRESSION, DEFAULT_SORT_DIRECTION);
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
// use the last sort expression and sort direction
GetDetails(this.SortExpression, this.SortDirection);
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
// get next sort direction
string sortDirection = GetSortDirection(e.SortExpression);
// get data with current sort expression and sort direction
GetDetails(e.SortExpression, sortDirection);
}
UPDATE
If you want to go to page 1 when sorting, just add GridView1.PageIndex = 0; to GridView1_Sorting:
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
GridView1.PageIndex = 0;
// get next sort direction
string sortDirection = GetSortDirection(e.SortExpression);
// get data with current sort expression and sort direction
GetDetails(e.SortExpression, sortDirection);
}

I want to do sorting on based on column of gridview, but event is not firing when I click on header of HeaderTemplete

I have created one gridview with custom column and want to perform sorting on them. When I click on column then no event is firing for sorting.
Below is the code which I have written
For .aspx page
<asp:GridView ID="grdConfigureCustomers" runat="server" AlternatingRowStyle- BackColor="Aqua" Width="1300px"
OnRowCommand="grdConfigureCustomers_RowCommand" OnRowEditing="grdConfigureCustomers_RowEditing"
OnRowUpdating="grdConfigureCustomers_RowUpdating" OnRowCancelingEdit="grdConfigureCustomers_RowCancelingEdit"
AutoGenerateColumns="false" AllowPaging="true" PageSize="5"
OnRowDeleting="grdConfigureCustomers_RowDeleting" ShowFooter="true"
onpageindexchanging="grdConfigureCustomers_PageIndexChanging" OnSorting="grdConfigureCustomers_Sorting" AllowSorting="true">
<HeaderStyle BackColor="AliceBlue" />
<Columns>
<asp:TemplateField HeaderText="Customer ID">
<ItemTemplate>
<asp:Label ID="lblCustomerId" runat="server" Text='<%# Eval("Customer_ID") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddCustomerId" runat="server"></asp:TextBox><span style="color:Red;">*</span>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
For .aspx.cs page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadCustomerConfigurationGridView();
}
}
private void LoadCustomerConfigurationGridView()
{
DataTable dt = new DataTable();
dt = sqlHelper.GetCustomerListInformation();
grdConfigureCustomers.DataSource = dt;
grdConfigureCustomers.DataBind();
Session["data"] = dt;
}
private void LoadCustomerConfigurationGridView(string srtexpr, string direc)
{
DataTable dt = new DataTable();
dt = sqlHelper.GetCustomerListInformation();
DataView dv = new DataView(dt);
dv.Sort = srtexpr + " " + direc;
grdConfigureCustomers.DataSource = dv;
grdConfigureCustomers.DataBind();
Session["data"] = dt;
}
protected void grdConfigureCustomers_Sorting(object sender, GridViewSortEventArgs e)
{
switch (e.SortExpression)
{
case "DateLogged":
if (e.SortDirection == SortDirection.Ascending)
{
LoadCustomerConfigurationGridView("DateLogged", "ASC");
}
else
{
LoadCustomerConfigurationGridView();
}
break;
}
}
Please let me know what I missed for sorting. Thanks in advance.
You need to specify the SortExpression property in the TemplateField like this:
<asp:TemplateField HeaderText="Customer ID" SortExpression="Customer_ID">
You need to enable sorting. EnableSorting="true" in your asp.net:Gridview.

Add Data to gridview dynamically in ASp.net

I have a gridview
<asp:GridView ID="gvOrders" runat="server">
<Columns>
<asp:BoundField DataField="Item" HeaderText="Item" SortExpression="Item" />
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="hdnItemID" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Quantity" HeaderText="Quantity" SortExpression="Quantity" />
</Columns>
</asp:GridView>
.............................................
Now i want Add Rows to gridview with data getting from Textbox/DropdownList.
And then how to access this GridData rows.
Assuming your GridView datasource is a DataTable named Dtable;
DataRow row = new DataRow();
row["columnName"] = textBox1.Text;
DTable.Rows.Add(row);
gvOrders.DataSource=Dtable;
gvOrders.DataBind();
Please try this, how it will help you.
Aspx Page:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name"></asp:BoundField>
<asp:BoundField DataField="Number" HeaderText="Number" SortExpression="Number"></asp:BoundField>
</Columns>
</asp:GridView>
C# Code:
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dt = new DataTable();
MakeDataTable();
}
else
{
dt = (DataTable)ViewState["DataTable"];
}
ViewState["DataTable"] = dt;
}
private void MakeDataTable()
{
dt.Columns.Add("Name");
dt.Columns.Add("Number");
}
protected void Button2_Click(object sender, EventArgs e)
{
AddToDataTable();
BindGrid();
}
private void AddToDataTable()
{
DataRow dr = dt.NewRow();
dr["Name"] = txtName.Text;
dr["Number"] = txtNumber.Text;
dt.Rows.Add(dr);
}
private void BindGrid()
{
GridView1.DataSource = dt;
GridView1.DataBind();
}

Categories

Resources