VS 2008 What's The Most Efficient Way To Sort A Gridview(vb.net)
Oct 28, 2010
What's the best way to do this? I have seen quite a few examples that use a Dataview etc. what is the best method. I'm thinking about speed issues when a grid has a few thousand records etc.
I have a requirement where 15 listviews have to be loaded on a web page.But only one shown at a time. Number of columns will be only 2 for each and Number of rows for every listview is very limited.The thing I am not able to decide is the sorting method.1. If I am using the datasource control, it automatically sorts my listview.2. If I am programmatically populating listview , I will have to sort my datatable and rebind to the listview.To use the second method I have to store the datatables in sessions.So taking that into consideration, will datasource control be more efficient ?
Just spent about 8 hours googling and looking through this forum for a solution on how to make sure that I can dynamically sort. Here is the situation.
I have 1 Gridview that displays 10 different scenarios based on what button is clicked.
I am also returning only top 10 records. I am doing all of the data binding pragmatically. So I have BoundFields, HyperLinkFields etc.
I also want to sort some records. When I change DataSource SQL statement the gridview somehow remembers what the last sort value was and it errors out saying that value "x" cannot be sorted because it does not exists.
Here I get an error that says that the data source does not support sorting? Doesnt it say gridview1.allowsorting = false;
I also tried gridview1.sort("", SortDirection.Ascending); This does nothin... except query my database one more time because i have a onSorting event that looks like this:
[Code]....
Here is an example of just one of those SLQ statements inside GetSQLQuery:
I am trying to do efficient paging with a gridview without using a datasource control. By efficient, I mean I only retrieve the records that I intend to show.I am trying to use the PagerTemplate to build my pager functionality.In short, the problem is that if I bind only the records that I intend to show on the current page, the gridview doesn't render its pager template, so I don't get the paging controls.It's almost as if I MUST bind more records than I intend to show on a given page, which is not something I want to do.
I have a GridView in ASP.Net 3.5. I added BoundFields as columns, set DataField and Header Text. Total I have 6 columns like that. Although I set "AllowSorting=True" in design view, when I run this page, all the columns didn't have hyper link that I can click on it and sort that particular column. I bind this column at code behind by using datatable. gv.DataSource = dtDispatch gv.DataBind()
I have a gridview with data. I want a button which is not part of the gridview. Then if I press a button the gridview is sorted by two colums. i.e column1 ascending column2 descending.
I am not looking to work with a Sqldatasource as I use a data access layer. So the sort would have to be from a datatable and databind or directly with the gridview.
I'm looking for a way to sort the rows of a datatable without setting the DefaultView.Sort to a specific column. I have a datatable in session that users can add records to. I want them to be able to sort the data by clicking on a button. But new records added after that need to show up at the bottom of the list until the sort button is clicked again.
I have a gridview in an updatepanel with sorting enabled and an event handler as follows:
protected void MyGridSort(object sender, GridViewSortEventArgs e) { var TheDirection = (e.SortDirection).ToString(); var TheColumn = (e.SortExpression).ToString();
I put a breakpoint just after these lines. Every time I press the column header, my variable TheDirection is always showing Ascending. Why is it not toggling from ascending to descending and back?
I have a repository that contains all of my LINQ queries for this project that I am working on. I am able to get the LINQ results to a DataTable and bind that to a gridview for displaying the data. Now I need to make the gridview sortable. I have set AllowSorting="true" and I have the OnSort event handled in a routine in the codebehind.
the specific example i am referring to is this site [URL] notice the sort by drop down list. basically i want to sort products according to price,name,popularity? do i have to requery the database and retreive the sorted data in gridview again, or should i already sort the items in the gridview that are already there? I tried to this but its the wrong approach, basically i was trying to repopulate data in the page load event, which was giving error.
I want to sort a GridView by clicking on the header. I guess all i need is the header name and then pass it into sql to get the data back sorted. How is it possible to get the header name?
Loading data into gridview, retieving data using linq,I have a method that accepts two paramters that would sort specific field and return the object to the gridviewi.e.
passing into the method GenerateData(string sortExp, string sortDir) sortExp = "Name", sortDir = "descending" linq query://works
I have a gridview with several columns, 3 of which I'd like to sort. The source for the data is held in the session.
protected void MyGridHistorySort(object sender, GridViewSortEventArgs e) { var TheColumn = (e.SortExpression).ToString(); TheDataHistory = (List<ViewDataHistoryModel>)Session["SessionDataHistory"]; var test = "data.DataDate"; var NewDataSource = from data in TheDataHistory orderby test select data; MyGridHistory.DataSource = NewDataSource; MyGridHistory.DataBind();
DataDate is a valid column in the list but the orderby statement doesn't work. Ideally, I'd like it to sort with the variable TheColumn by writing something like test = "data."+TheColum; and then add a sort direction based on a boolean. I looked at the OrderBy extension method NewDataSource.OrderBy(test); but that doesn't work either.
I'm trying to sort records in the gridview right after a radio button is selected. My approach is with the dataview, but because the dataset variable doesn't survive a round trip to the server, I don't know how to make this happen.
Public Sub GetCustomers() db.RunProcedure("usp_customers_get_all") db.doSort(radList.SelectedValue) gvCustomers.DataSource = db.MyView End Sub Protected Sub radList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radList.SelectedIndexChanged If radList.SelectedValue = 0 Then db.doSort(0) gvCustomers.DataSource = db.MyView End If If radList.SelectedValue = 1 Then db.doSort(1) gvCustomers.DataSource = db.MyView End If End Sub Public Sub doSort(ByVal strIn As Integer) If strIn = 0 Then MyView.Sort = "lastname, firstname" Else MyView.Sort = "username" End If End Sub Public Sub RunProcedure(ByVal strName As String) Dim objConnection As New SqlConnection(mstrConnection) Dim mdbDataAdapter As New SqlDataAdapter(strName, objConnection) Try mdbDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure Me.mDataset.Clear() mdbDataAdapter.Fill(mDataset, "tblCustomers") MyView.Table = mDataset.Tables("tblCustomers") Catch ex As Exception Throw New Exception("stored procedure is " & strName.ToString & " error is " & ex.Message) End Try End Sub
My Gridview sort is working only first time. My Gridview sort only first time when I click on any column
I want ASC > DESC
Again DESC > ASC
and Again ASC > DESC this way my sort should work
I have changed my code
I added Gridview binding to PAge_Load function
Code is below
Public Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim myUserInfo As GCS_User_Info = Session("UI") If Not Page.IsPostBack Then GRDView.DataSource = GetSortableData(String.Empty) 'System.Drawing.FontFamily.Families GRDView.DataBind()
I was given help in a previous topic located here: Accessing Gridview In Another Form In this topic I had gridview rows that are selectable and a search window that returned search results. We found a way for me to select a row in the parent window of the search one. My issue now is that when the parent windows gridview is sorted, the function no longer selects the correct row. I was wondering if there was any way to access the gridviews sort expression and direction, or some other way I can do this so it accounts for sorting. Relavent code is as follow: This is in my parent window
<script type = "text/javascript"> function selectRow(index) { //Retrieve a reference to the table that represents the GridView var gridView = document.getElementById('<%=gvSideList.ClientID%>'); if(gridView) { //If able to get a reference to the table representing the GridView... var doPostbackArgument='Select$'+index; __doPostBack('<%=gvSideList.ClientID%>',doPostbackArgument); } }
This is in the child window
<script type = "text/javascript" > function selecttherow(index) { window.opener.selectRow(index); } </script> protected void gvresults_SelectedIndexChanged(object sender, EventArgs e) { //declare variables GridViewRow row; int index; int id; //retrieve index, row, and id from gvresults index = gvresults.SelectedIndex; row = gvresults.Rows[index]; id = Convert.ToInt32(row.Cells[5].Text); //fill a datatable from general with id's for selection SqlCommand cmd = new SqlCommand("SELECT ID FROM General", csbg); cmd.Parameters.AddWithValue("@id", id); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); //loop through the dt and find the index of the matching id from the search window for (int i = 0; i < dt.Rows.Count; i++) { if (dt.Rows[i]["ID"].Equals(id)) { //execute script to select the matching row in the dataentry page string script = ""; script += "selecttherow("; script += i; script += ");"; ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "selecting", script, true); break; } } }
Let me know if you need me to further clarify anything.
i want to sort my Gridview rows by a template column that is not bound to any database field. This template coulmn just has a label whose text i set in code depending on a value in a different column that is databound. So am stuck on how to set its sortExpression since its not linked to an column.
My program running good. But i try to add up-down icon on my gridView header. but if i make it, My break point should drop below "if comparison" For example; field.SortExpression=Category but every time CustomersGridView.SortExpression is empty when gridview.SortExp is not empty.
foreach (DataControlField field in CustomersGridView.Columns) { if (field.SortExpression == CustomersGridView.SortExpression) { return CustomersGridView.Columns.IndexOf(field); } } i need : foreach (DataControlField field in CustomersGridView.Columns) { if (field.SortExpression == "Category") { return 2; } } CustomersGridView.SortExpression must not be empty!!!!! MY source: <head runat="server"> <title></title> <link type="text/css" href="StyleSheet.css" rel="stylesheet" /> </head> <body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"> <ContentTemplate> <asp:GridView ID="gvCustomers" runat="server" CssClass="tablestyle" AllowSorting="true" OnRowDataBound="GvCustomers_RowDataBound" AutoGenerateColumns="false"> <AlternatingRowStyle CssClass="altrowstyle" /> <HeaderStyle CssClass="headerstyle" /> <RowStyle CssClass="rowstyle" /> <Columns> <asp:BoundField HeaderText="Kategori" DataField="Category" SortExpression="Category" /> <asp:BoundField HeaderText="Tarih" DataField="Date" SortExpression="Date" /> </Columns> </asp:GridView> </ContentTemplate> </asp:UpdatePanel> protected void GvCustomers_RowDataBound(object sender, GridViewRowEventArgs e) { GridView gridView = (GridView)sender; if (gridView.SortExpression.Length > 0) { int cellIndex = -1; foreach (DataControlField field in gridView.Columns) { if (field.SortExpression == gvCustomers.SortExpression) { cellIndex = gridView.Columns.IndexOf(field); break; } } if (cellIndex > -1) { if (e.Row.RowType == DataControlRowType.Header) { // this is a header row, // set the sort style e.Row.Cells[cellIndex].CssClass += (gridView.SortDirection == SortDirection.Ascending ? " sortascheader" : " sortdescheader"); } else if (e.Row.RowType == DataControlRowType.DataRow) { // this is an alternating row e.Row.Cells[cellIndex].CssClass += (e.Row.RowIndex % 2 == 0 ? " sortaltrow" : " sortrow"); } } } }