gridview sorting problem in paging - asp.net

In gridview
when i go to nextpage(page2) and clicked on header to sort, it is sorting all the data. i need to sort only the data in page2
here is my code
DataTable dataTable = ViewState["HospAcc"] as DataTable;
if (dataTable != null)
{
DataView dv = new DataView(dataTable);
dv.Sort = string.Format("{0} {1}", e.SortExpression, Direction);
Direction = (Direction == "ASC") ? "DESC" : "ASC";
//Bind resutls
gvHospAcc.DataSource = dv;
gvHospAcc.DataBind();
}
and one more thing is when i go to second page my sort is getting collapsed
Thank you

How are you getting your data into the gridview? You could manually page the data that goes into the gridview; that way, when you click on the header, it will only sort the data on that page, since there's no other data besides that.

Related

Cast error on GridView Sorting event

I'm intercepting the RowDatabound event and using:
DbDataRecord record = (System.Data.Common.DbDataRecord)e.Row.DataItem;
to get access to the unbound data source columns. It works fine on page load and when I apply a filter to the dataset. However, when I attempt to initate a sort on a GridView Column, I get :
Error: Unable to cast object of type 'System.Data.DataRowView' to type 'System.Data.Common.DbDataRecord'
I think I've traced the root issue back to the bind method used in the sort:
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
if (eventArgs != null)
{
DataSet SortedData = new DataSet();
ds.Tables[0].DefaultView.Sort = eventArgs.SortExpression + " " + GetSortDirection(eventArgs.SortExpression);
SortedData.Tables.Add(ds.Tables[0].DefaultView.ToTable());
GridView1.DataSource = SortedData;
}
else
{
GridView1.DataSource = ds;
}
GridView1.DataBind();
}
I remember this was a major pain to figure out because only Dataset had a Sort Property
Since you assign a DataSet to GridView1.DataSource, then the type of e.Row.DataItem in the RowDatabound event will be a DataRowView instead of a System.Data.Common.DbDataRecord. You need to change this:
DbDataRecord record = (System.Data.Common.DbDataRecord)e.Row.DataItem;
to this:
DataRowView record = (DataRowView)e.Row.DataItem;
Instead of trying to sort the Dataset, I appended the sort direction and column from the viewstate to the query before binding it to the grid using SqlDataReader. Looks like I went out of my way to make a simple thing hard to begin with...

Selecting Edit on row returns wrong row after sorting

I am currently setting my GridView AllowSorting = true. The sorting works fine, but when I click on the edit button for a specific row after sorting, the wrong row gets returned. It edits the row that was previously in the position of the current row before sorting.
Here is my code in the Sorting event.
string sortExpression = e.SortExpression;
string direction = string.Empty;
if (SortDirection == SortDirection.Ascending)
{
SortDirection = SortDirection.Descending;
direction = " DESC";
}
else
{
SortDirection = SortDirection.Ascending;
direction = " ASC";
}
DataTable table = Session["WebUserDT"] as DataTable;
table.DefaultView.Sort = sortExpression + direction;
grdWebUser.DataSource = table;
grdWebUser.DataBind();
Any idea how to solve this?
You should get dataTabe in an WiewState and in rowEditing function you should set this as gridview datasource and bind the gridview and it will be solved

Mutliple dropdowns and values on the Paging

I have a GridView and I populate it via a DATASET . Three of its columns are three DropDownLists and AllowPaging is set to true for the grid view. My problem is when I choose a value on anyone of the ddl and click on serach button i get the data on the gridview which will have paginig, but when i click on the second page i loose teh filtered calue onthe drop down and i again get the earlier dataset.
Is there any way/idea to persist the selected values? Thanks for your help.
Please can you help me with this. if i am not filtering anyone of teh dropdown and then clicking on the second or third page i get the relevant data of that particular page. teh only problem is when i have a value selected on the dropdown .
code:
button click:
{
string _strBU = BUDropDownList.SelectedValue;
string _strOU = OUDropDownList.SelectedValue;
string _strPortalID = !string.IsNullOrEmpty(TxtEmpPortalID.Text.Trim()) ? TxtEmpPortalID.Text.Trim() : string.Empty;
string _strRU = RUDropDownList.SelectedValue;
string _strMngrPortalID = System.Web.HttpContext.Current.User.Identity.Name.ToString();
_strMngrPortalID = _strMngrPortalID.Substring(4, 6);
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString = "server=;uid=;pwd=;database=HROrgchartDB";
sqlConnection.Open();
SqlCommand sqlEmployeeDetailsCommand = new SqlCommand();
sqlEmployeeDetailsCommand.Connection = sqlConnection;
sqlEmployeeDetailsCommand.CommandText = "EmployeeSearch";
sqlEmployeeDetailsCommand.CommandType = CommandType.StoredProcedure;
sqlEmployeeDetailsCommand.Parameters.Add(new SqlParameter("#BU", SqlDbType.VarChar, 50)).Value = _strBU;
sqlEmployeeDetailsCommand.Parameters.Add(new SqlParameter("#OU", SqlDbType.VarChar, 50)).Value = _strOU;
sqlEmployeeDetailsCommand.Parameters.Add(new SqlParameter("#PORTALID", SqlDbType.VarChar, 6)).Value = _strPortalID;
sqlEmployeeDetailsCommand.Parameters.Add(new SqlParameter("#RU", SqlDbType.VarChar, 50)).Value = _strRU;
sqlEmployeeDetailsCommand.Parameters.Add(new SqlParameter("#ManagerPortalID", SqlDbType.VarChar, 6)).Value = _strMngrPortalID;
SqlDataAdapter da = new SqlDataAdapter(sqlEmployeeDetailsCommand);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds != null)
{
// gvAddorRelease.Visible = true;
gridReportees.DataSource = ds;
Cache["D2"] = ds;
gridReportees.PageIndex = 0;
gridReportees.DataBind();
}
else
{
}
sqlConnection.Close();
}
}
event for paging :
gridReportees_PageIndexChanging:
{
gridReportees.PageIndex = e.NewPageIndex;
DataSet ds = new DataSet();
ds=(DataSet)Cache["D2"];
gridReportees.DataSource= ds;
gridReportees.DataBind();
}
Problem:
When you click on the next page, dropdown also rebinds due to which there selected index changed to 0.
Solution:
When you press the search button at that time you have to save the selectedvalues of the 3 dropdownlists. the dropdowns are present inside your gridview,so first you have to get the gridview row index. You can get the row index from gridveiw_selectedindexchange event. [Hint]
ViewState["svalue1"] = ((DropDownList) gv.Rows[index].FindControl("dropdownlistID")).Text;
// also get the selected values of other 2 dropdowns
Now after getting the selectedvalues you have to set the dropdwonlist.selected value to the values which we have saved in the ViewState.
gridReportees_PageIndexChanging()
{
// After binding the grid
// in this metho set the dropdown seleted value
// example get a reference of your dropdown
DropDownList ddl1 = (DropDownList) gv.Rows[index].FindControl("dropdownlistID");
ddl.SelectedValue = ViewState["svalue1"].ToString();
// follow the same steps for other 2 dropdownlists
}
Hope that it works for you.

GridView as DataTable source sorts only for the first time

I implemented sorting on my GridView with a DataTable as DataSource by using code from this MSDN link. However, my grid sorts for the first time when I click any column, and after that it does not sort on clicking any other column.
Code in the PageLoad() event -
if (!Page.IsPostBack)
{
HView hv = new HView ();
DataTable HTable = new DataTable("hTable");
HTable = hv.FillTable();
Session["hTable"] = HTable;
GridView2.DataSource = Session["hTable"];
GridView2.DataBind();
}
Code in the Sorting event -
protected void GridView2_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable notesDT = Session["hTable"] as DataTable;
if (notesDT != null)
{
notesDT.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortDirection);
GridView2.DataSource = Session["hTable"];
GridView2.DataBind();
}
}
Does anybody have an idea of what I may be doing wrong?
EDIT: I just realized this. If I select a particular row, I have another view that gets populated with details about that row. When I view some rows details first before trying to sort any columns, then sorting works perfectly fine, any number of times. However, if I try to sort before selecting a row, it works only once.
You are using the DataTable as DataSource in the sorting event, but you should use the sorted view instead. Sorting the view won't change the sort order of the data in the table, just the order in the view.
protected void GridView2_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable notesDT = Session["hTable"] as DataTable;
if (notesDT != null)
{
notesDT.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortDirection);
GridView2.DataSource = notesDT.DefaultView;
GridView2.DataBind();
}
}
Edit: Although that i've just noticed that you're using rhe same code from MSDN.
You could also try to create a new DataTable from the view:
GridView2.DataSource = notesDT.DefaultView.ToTable(true);
You don't need stored the data table into a session. Actually putting the entire data table into session is not a good idea at all. Any particular reason for that?

Sorted gridview selects wrong row

I have a gridview (actually a SPgridview)
And i made the columnname clickable so the users can sort the rows using the data.
And that works fine.
The problem occurs when users try to select a row after they sorted the data.
I can see that the gridview kinda "forgets" how the rows were sorted and selects the row that was at the clicked index before it got sorted..
How do i fix that?
I tried sorting the row again after the user selects a row, but that doesnt seem to work.
And should the gridview remember the fact that it was just sorted?
Thanks in advance :)
When you handle the Sorting event set a session variable set it to the sort direction and use it when you rebind your datasource.
protected void gridview_Sorting()
{
// BIND DATA Function
BindData();
DataTable dt = gridview.DataSource as DataTable;
if (dt != null)
{
//Sort the data.
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
Session["sort"] = dt.DefaultView.Sort;
gridview.DataSource = dt;
gridview.DataBind();
}
}
// bind data function//
private void BindData()
{
DataTable dt = GetDataTable();
if (Session["sort"] != null)
{
//Sort the data.
dt.DefaultView.Sort = Session["sort"].ToString();
}
gridview.DataSource = dt;
gridview.DataBind();
}
Make sure that you are not rebinding the grid after a postback.
if(!IsPostBack)
{
gridView.DataSource = yourDataSource;
gridView.DataBind();
}
Are you grabbing the selected row by it's row index or by the unique identifier of the data you are wanting to edit? If you're getting by row index, it may be 'forgetting' since you are recreating the Grid on OnPostBack. Try iterating through the data and select it by it's unique ID, not its row index.
Check Johans blog regarding SPGridView and LinqDataSource
I'd made a number of sortable GridViews, but none with row command interaction before today, when I stumbled on this problem. Mine is a "plain" GridView, not SPgridview. I found this works:
In bindData(), if we have not created a DataTable and put it in the Session object, do so. Otherwise, we'll use the existing, sorted DataTable:
if (Session["dtbl"] == null) {
Session["dtbl"] = method_to_fetch_datatable();
}
gv.DataSource = Session["dtbl"] as DataTable;
gv.DataBind();
In the GridView's handling of row commands that INSERT, UPDATE or DELETE underlying data, refresh the Session object, maintaining the sort, if there is one:
Session["dtbl"] = method_to_fetch_datatable();
if (ViewState["SortExpression"] != null) {
DataTable dt = Session["dtbl"] as DataTable;
dt.DefaultView.Sort = ViewState["SortExpression"] as string;
}
bindData();
I got it working. (kinda)
In the sorting event i saved the sortexpression (the name of the column used to sort by)
and the sortdirection ascending or descending.
Then i make the datasource for the gridview and databind, and after databinding it, i use the gridview.sort command to sort by the values i saved in viewstate.
That works fine, only one problem.
When sorting i made it switch direction after pressing the same column more than one time.
Now it thinks i keep pressing the column title, so it keeps reversing the sorting.
But i tempererarely made it only sort in one direction.
And now im playing with the sender object in the sorting event, im thinking that if i could get some info about whats causing the event i could tell it to only switch direction based on the sender.
Thanks :)

Resources