The Problem: You are trying to create an ASP.net GridView that automatically populates on any dataset, as well as automatically sorts, but for some reason whenever you click the headers to sort the GridView, the data doubles.
The Cause: I originally omitted crucial line
gv.Columns.Clear();
in the code sample below. For whatever reason I got it stuck in my head that the data was doubling, not the columns.
The Solution: Just add in the .Clear() line of code to the Gridview population routine and the problem is solved.
The Code:
All the code you need in the .aspx page:
<asp:GridView ID=”gv” AllowSorting=”true” runat=”server” AutoGenerateColumns=”False” onsorting=”gv_Sorting”></asp:GridView>
All the code you need to initially populate the GridView in the .cs pages
private DataSet GenDataSet() { // Delcare a DataSet and Table DataSet ds = new DataSet(); DataTable dt = new DataTable(); DataRow dtRow; dt.Columns.Add("MNumber"); dt.Columns.Add("Legal Name"); dt.Columns.Add("Email"); dt.Columns.Add("Level"); dtRow = dt.NewRow(); dtRow["MNumber"] = "A"; ; dtRow["Legal Name"] = "A"; dtRow["Email"] = "A"; dtRow["Level"] = "A"; dt.Rows.Add(dtRow); dtRow = dt.NewRow(); dtRow["MNumber"] = "B"; ; dtRow["Legal Name"] = "B"; dtRow["Email"] = "B"; dtRow["Level"] = "B"; dt.Rows.Add(dtRow); dtRow = dt.NewRow(); dtRow["MNumber"] = "C"; ; dtRow["Legal Name"] = "C"; dtRow["Email"] = "C"; dtRow["Level"] = "C"; dt.Rows.Add(dtRow); dtRow = dt.NewRow(); dtRow["MNumber"] = "D"; ; dtRow["Legal Name"] = "D"; dtRow["Email"] = "D"; dtRow["Level"] = "D"; dt.Rows.Add(dtRow); dtRow = dt.NewRow(); dtRow["MNumber"] = "E"; ; dtRow["Legal Name"] = "E"; dtRow["Email"] = "E"; dtRow["Level"] = "E"; dt.Rows.Add(dtRow); ds.Tables.Add(dt); //note this is columns gv.Columns.Clear(); foreach (DataColumn col in ds.Tables[0].Columns) { BoundField bfNew = new BoundField(); //Initalize the DataField value. bfNew.DataField = col.ColumnName; //Initialize the HeaderText field value. bfNew.HeaderText = col.ColumnName; bfNew.SortExpression = col.ColumnName; //Add the newly created bound field to the GridView. gv.Columns.Add(bfNew); } return ds; }
That’s it!
This post originally appeared on the Stronico blog – with the absorption of Stronico into Digital Tool Factory this post has been moved to the Digital Tool Factory blog
|
Written By Steve French |
Leave a Reply