views:

99

answers:

4

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..

A: 

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];
jussij
A: 

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.

Mark Byers
A: 

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.

Justin C
A: 

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.

Joel Etherton