c# asp.net gridview not sorting - c#

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using BiscomFax;
namespace FaxServer
{
public partial class _Default : System.Web.UI.Page
{
public const string vsColumn = "Column";
public const string vsSortDirection = "SortDirection";
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
ViewState[vsColumn] = "";
List_Click(ActivityButton, e);
}
protected void List_Click(object sender, EventArgs e)
{
//using (new Impersonator("administrator", "mlabs.com", "100%secure*"))
//{
try
{
Fax fax = new Fax();
ConnObj cnObj = GetConfiguration();
Button btn = (Button)sender;
string sort = "";
DataTable dt = new DataTable();
switch (btn.CommandName)
{
case "Activity":
sort = "DateTime";
dt = fax.GetActivityLog(cnObj.faxDir, cnObj.faxUsername, cnObj.faxPassword);
break;
case "Message":
sort = "DateTime";
dt = fax.GetMessageStatus(cnObj.faxDir, cnObj.faxUsername, cnObj.faxPassword);
break;
case "Pending":
sort = "DeliveryTime";
dt = fax.GetPendingList(cnObj.faxDir, cnObj.faxUsername, cnObj.faxPassword);
break;
default:
sort = "DateTime";
dt = fax.GetActivityLog(cnObj.faxDir, cnObj.faxUsername, cnObj.faxPassword);
break;
}
GridView1.DataSource = dt;
GridView1.Sort(sort, SortDirection.Descending);
GridView1.DataBind();
}
catch (Exception ex)
{
throw ex;
}
//}
}
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = GridView1.DataSource as DataTable;
if (dt != null)
{
DataView dv = new DataView(dt);
string oldSort = ViewState[vsColumn].ToString();
dv.Sort = e.SortExpression + " " + convertSorDirectionToSql(e.SortDirection);
if (dv.Sort == oldSort)
dv.Sort = e.SortExpression + " " + convertSorDirectionToSql(SortDirection.Descending);
ViewState[vsColumn] = dv.Sort;
GridView1.DataSource = dv;
GridView1.DataBind();
}
}
i am having a very difficult time sorting the contents of this gridview, i know that i am binding correctly becuase the data is showing but the data does not get sorted at all by DateTime. what am i doing wrongly?

Lets look at this line
dv.Sort = e.SortExpression + " " + convertSorDirectionToSql(e.SortDirection);
While testing, when you put a breakpoint on this line what value did e.SortExpression have?

Your databind is correct.
here is a nice article for sorting in gridview:
http://www.mikepope.com/blog/DisplayBlog.aspx?permalink=1418
[update]
Your code has several inconsistency. You probably need to implement it again.
allowsorting must be true
each grid column must declare the sortexpression
you can't read the data back from the gridview's datasource
you need to read the data from your database on each postback, i.e. sorting
here is a good example in C#:
http://programming.top54u.com/post/ASP-Net-2-0-Gridview-Sorting-Using-C-sharp.aspx

You could sort the datatable by setting it's property datatable.defaultview.sort. Don't know of the top of my head whether you need to bind the datatable or the datatable.defaultview after that though.

Try This code
protected void grdList1_Sorting(object sender, GridViewSortEventArgs e)
{
fillgrid();
string sortstr = e.SortExpression;
DataView dview = new DataView(dtable);
if (sortstr == "asc")
dview.Sort = e.SortExpression + " desc";
else
dview.Sort = e.SortExpression + " asc";
grdList1.DataSource = dview;
grdList1.DataBind();
}

just check allowsorting property on aspx page in gridview control
It may be false.
please make it true and then check sorting.

Related

ASP.NET GridView Sort using DataTable.Select

Is it possible to sort an ASP.NET GridView using DataTable.Select("", sortExpression)?
I have a regular GridView with AllowSorting="true" and OnSorting="grdEmployees_Sorting".
protected void grdEmployees_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = getDataTable();
var sortExprOrder = e.SortDirection == SortDirection.Ascending ? " ASC" : " DESC";
var rows = dt.Select("", string.Format(e.SortExpression + "{0}", sortExprOrder));
grdEmployees.DataSource = rows;
grdEmployees.DataBind();
}
Not sure why, but this does not work. The grid shows a bunch of rows with three columns, RowError, RowState, and HasErrors (contains rows with all empty checkboxes).
Am I doing something wrong?
You don't need select for sorting DataTable.Select is for filtering
This how you sort
protected void grdEmployees_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = getDataTable();
var sortExprOrder = e.SortDirection == SortDirection.Ascending ? " ASC" : " DESC";
DataView dv = new DataView(dt);
dv.Sort = string.Format("{0} {1}",
e.SortExpression, sortExprOrder);
grdEmployees.DataSource = dv;
grdEmployees.DataBind();
}

sorting on searched records not working

I am having problem in sorting the searched records in a gridview to ascending and descending directions. I have applied the following code to normal gridview (all records) and it is working all fine but when I try to search any records from all records, and try to sort those searched records, following code neither performs any actions nor throws any errors: Following code is applied for sorting:
protected void GridView2_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView1(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView1(sortExpression, ASCENDING);
}
}
private void SortGridView1(string sortExpression, string direction)
{
DataTable dt = SearchTable().Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
GridView2.DataSource = dv;
GridView2.DataBind();
}
Search function code is:
public DataSet SearchTable()
{
string sql1 = "SELECT * from dbo.Documents1";
bool flag = false;
if (!txtRef.Text.Equals(""))
{
if (flag == false)
{
sql1 = sql1 + " where Ref LIKE N'%" + txtRef.Text + "%'";
flag = true;
}
else
{
sql1 = sql1 + " and Ref LIKE N'%" + txtRef.Text + "%'";
}
}
if (!txtSubject.Text.Equals(""))
{
if (flag == false)
{
sql1 = sql1 + " where Subject LIKE N'%" + txtSubject.Text + "%'";
flag = true;
}
else
{
sql1 = sql1 + " and Subject LIKE N'%" + txtSubject.Text + "%'";
}
}
}
using (SqlConnection con = new SqlConnection("Data Source=MEHDI-PC\\SQLEXPRESS;Initial Catalog=PIMS;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = sql1 + ";";
//cmd.CommandType = CommandType.StoredProcedure;
con.Open();
//dataset object to get all select statement results
DataSet ds = new DataSet();
//sql dataadoptor to fill dataset
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
adp.Fill(ds);
}
if (con.State == ConnectionState.Open)
{
con.Close();
}
return ds;
}
}
}
PageLoad Event function is:
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = rpt.Documents1s.ToList();
GridView1.DataBind();
if (!IsPostBack)
{
BindGrid();
MultiView1.SetActiveView(vHome);
btnBacktoHome.Visible = false;
lblStatus.Visible = false;
}
}
I cant understand where I am going wrong. when clicked on a column to sort, it took me out of searched records and sorted "All-Records" which are placed in GridView1 while searched-records are placed in GridView2 as shown in the code. what I am failed to understand is, why programs jumps to GridView1 and sort all-records there when I click to click to sort searched-records in GridView2. Any help will be much appreciated. Thanks in advance.
Did you use the gridview binding code in inside of !ISPostBack ? like
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//Grid Binding code
}
}
Edit for you page load code(Must add the databind in inside of !IsPostBack)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = rpt.Documents1s.ToList();
GridView1.DataBind();
BindGrid();
MultiView1.SetActiveView(vHome);
btnBacktoHome.Visible = false;
lblStatus.Visible = false;
}
}

How to change GridView Column type from TextBox to LinkButton

I need to know how to allow Gridview column to accept LinkButton. By default, GridView Column is set to accept TextBox controls but I need to have a LinkButton control. My code is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.IO;
using System.Data.Common;
using System.Globalization;
namespace GridView_Tutorial
{
public partial class GridView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=Mehdi-PC\\SqlExpress; Initial Catalog=PIMS; Integrated Security=true");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT cat_id, cat_name FROM quest_categories", con);
DataTable dt = new DataTable();
da.Fill(dt);
//add a blank row to returned DataTable
DataRow dr = dt.NewRow();
dt.Rows.InsertAt(dr, 0);
//creating the first row of Gridview to be editable
GridView1.EditIndex = 0;
//Data Sourcing and binding
GridView1.DataSource = dt;
GridView1.DataBind();
//Changing the Text for Inserting a New Record
((LinkButton)GridView1.Rows[0].Cells[0].Controls[0]).Text = "Insert";
if (con != null)
{
con.Close();
}
}
}
}
Following line of code is throwing error:
((LinkButton)GridView1.Rows[0].Cells[0].Controls[0]).Text = "Insert";
Error Message is:
InvalidCastException is unhandled by the user.
Unable to cast object of type 'System.Web.UI.WebControls.TextBox' to type 'System.Web.UI.WebControls.LinkButton'.
When I change the code from:
((LinkButton)GridView1.Rows[0].Cells[0].Controls[0]).Text = "Insert";
to
((TextBox)GridView1.Rows[0].Cells[0].Controls[0]).Text = "Insert";
Error goes away, and code inserts a textbox in datatable.
Please help me to insert a LinkButton instead of a TextBox.
Regards
Please try with the below code snippet.
ASPX
<asp:GridView ID="GridView1" runat="server"
onrowdatabound="GridView1_RowDataBound">
</asp:GridView>
ASPX.CS
protected void Page_Load(object sender, System.EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Shipper", typeof(string));
dt.Columns.Add("ShipperTemp", typeof(string));
dt.Rows.Add("CShipper1", "1");
dt.Rows.Add("BShipper2", "2");
dt.Rows.Add("AShipper1", "1");
dt.Rows.Add("EShipper1", "2");
dt.Rows.Add("DShipper4", "4");
DataRow dr = dt.NewRow();
dt.Rows.InsertAt(dr, 0);
//creating the first row of Gridview to be editable
GridView1.EditIndex = 0;
//Data Sourcing and binding
GridView1.DataSource = dt;
GridView1.DataBind();
//Changing the Text for Inserting a New Record
//((LinkButton)GridView1.Rows[0].Cells[0].Controls[0]).Text = "Insert";
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState == DataControlRowState.Edit)
{
e.Row.Cells[0].Controls.Clear(); // Comment this line if you do not want to hide Textbox from First Cell first Row
LinkButton btn = new LinkButton();
btn.ID = "ID";
btn.Text = "Insert";
e.Row.Cells[0].Controls.Add(btn);
}
}

Issues with paging and sorting in asp.net gridview

I have a grid view where I am implementing both paging and sorting. When I sort the table and select page 2, then the sorting is lost and the second 20 records are displayed in desc as mentioned in gridview binding
private DataSet BindGridView(string field)
{
DataSet ds = new DataSet()
string userQuery = "Select tbl_User.UserID, tbl_User.FirstName from tbl_user order by tbl_user.UserID desc";
UserTable.DataBind();
return ds;
}
<asp:GridView ID="UserTable" runat="server" PageSize="20" AllowPaging="True"
SelectedIndex="0" DataKeyNames="UserID" OnRowDataBound="UserTable_RowDataBound"
AutoGenerateColumns="false" OnPageIndexChanging="gridView_PageIndexChanging" AllowSorting="true" OnSorting="gridView_Sorting">
How can I retain the sorting and perform the paging, I store the sort state in the session, how can i use that to perform paging.
protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
UserTable.PageIndex = e.NewPageIndex;
UserTable.DataBind();
DataView myView = new DataView(BindGridView(Session["useremail"].ToString()).Tables[0]);
}
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = null;
if ((Session["UsersortExpression"] == null))
{
sortExpression = null;
}
else
{
sortExpression = (Session["UsersortExpression"].ToString());
}
if (sortExpression == e.SortExpression)
{
sortExpression += " DESC";
}
else
{
sortExpression = e.SortExpression;
}
DataView myView = new DataView(BindGridView(Session["useremail"].ToString()).Tables[0]);
myView.Sort = sortExpression;
UserTable.DataSource = myView;
UserTable.DataBind();
//save sort state
Session.Add("UsersortExpression", sortExpression);
}
You could apply sorting on your source query using ViewState String vars to store sort field and sort direction:
Ensure ViewState vars are set with defaults:
ViewState["sortDir"] = "DESC";
ViewState["sortField"] = "tbl_user.UserID";
Then, modify your query string:
string userQuery =
"Select tbl_User.UserID, tbl_User.FirstName " +
"from tbl_user " +
"ORDER BY " + (String)ViewState["sortField"] + " " + (String)ViewState["sortDir"];
Include in OnSorting:
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
// Set new sort direction and sort field
if ((String)ViewState["sortDir"] == "DESC"){ViewState["sortDir"] = "ASC";}
else { ViewState["sortDir"] = "DESC"; }
ViewState["sortField"] = e.SortExpression;
// Rebind
...
}
This way, your source data is pre-sorted and you don't need to worry about using myView.Sort or running into any paging/sorting conflicts.
Please refer to this article about paging and sorting in asp.net gridview.
Hope that helps.

How to convert a GridView to DataTable and sort the DataTable?

I want to convert my GridView to a DataTable. Note: The GridView doesn't have a DataSource!
I want to sort the DataTable and put it back to the GridView, is it possible? Important is that my GridView must be sorted.
Thank you in advance.
Put your DataTable in a ViewState when you bind for the first time.
gridView1.DataBind();
ViewState["dtbl"] = YourDataTable
and then do like...
protected void ComponentGridView_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = ViewState["dtbl"] as DataTable;
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " + ConvertSortDirection(e.SortDirection);
ComponentGridView.DataSource = dataView;
ComponentGridView.DataBind();
}
}
private string ConvertSortDirection(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;
case SortDirection.Descending:
newSortDirection = "DESC";
break;
}
return newSortDirection;
}
Also take a look at this MSDN article http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting.aspx

Categories