How to fill a dataset after getting a gridview?
I have a gridview which has many columns.. the columns are got separately and displayed in a gridview.
now i need to sort this gridview but i cannot do that.... i have found a 开发者_如何学运维way but i will need to get the gridview in a datatable or a dataset.... is there a a way to do this?
DataSet ds= new DataSet();
ds = Gridview1.????
please help..
One way to do this would be to use a DataGridView and use the DataSource property of this control:
OleDbConnection conn = new OleDbConnection(connection);
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = new OleDbCommand("select * from my_table", conn);
DataSet dataset = new DataSet();
// fill the data set using the query defined in the adapter
adapter.Fill(dataset);
// fill the grid with the data set
DataGridView1.DataSource = dataset.Tables[0];
You can create a new class to represent each row in the table, and bind to a list of objects of that class. Then to fix the sorting you can wrap your data source in a SortableBindingList. You can use the files PropertyComparer.cs and SortableBindingList.cs from this zip file and use it like this:
gridView1.DataSource = new SortableBindingList<cLineItem>(list);
I've tested this with a DataGridView. I assume it also works with a GridView.
How are you populating the GridView, with a SqlDataSource (or similar) in the ASPX or with code in the .cs codebehind?
It is possible to iterate through the child controls and cast objects if you know the exact make-up but that is not fun. If there is any way to copy the data before binding it to the GridView that would be more typical.
I would create a shared method or maybe even a class (depending on how often you would need this functionality) that would be responsible fore receiving a set of data collections (however you are retrieving these columns of data), and compiling it into a coherent typed datatable. This would add all of the built-in sorting features you would get and would also give you the ability to have a singular compiled source for your total data. Then you could use the DefaultView to sort/mix/filter this data without affecting its original nature.
精彩评论