sqlchild
sqlchild

Reputation: 9074

Sorting columns in datagridview control which are directly displayed from the sql database table

I have a winform with textboxes , a datagridview control and a submit button which sends the data from the textboxes to the sql database table and displays that data into the datagridview in a datatable.

Now, I want that when the submit button is pressed then the datagridview is refreshed and sorted according to a specified column, but the columns are directly displayed from the sql server table and are not separately specified in the properties of the datagridview control in visual studio IDE.

So how do i do this? When i do this:

DataGridViewColumn d = new DataGridViewColumn();
d.Name = "ItemID";
dataGridView1.Sort(d,ListSortDirection.Ascending);

Then it gives the error saying : The specified column not present. This is expected because the ItemID column is coming directly from the database and not explicitly added in the DataGridView control.

Upvotes: 0

Views: 1088

Answers (1)

manji
manji

Reputation: 47978

After filling the DataGridView with data, the column is already present in the DataGridView, so fetch it and use it for sorting:

DataGridViewColumn col = dataGridView1.Columns["ItemID"];
dataGridView1.Sort(col,ListSortDirection.Ascending)

Upvotes: 2

Related Questions