say I display a datatable on a datagridview, then the user sorts it, and selects a row... I want to do something with the original datatable to the same row... but the row indexes in the datagridview and datatable are now out of sync. How should I be doing this?
If your table has a primary key, get it from the selected row, then use the DataTable.Select() method to locate that row in the datatable.
Assuming that the source for the data has an index, you can store the index as a hidden column in your datagridview.
A couple things come to mind.
You can requery the DataTable's data source.
You can programmatically add a Column to your DataTable that acts as an index of the DT's original row order. When you want to restore the sort order, sort on this column. I've done this. You can set the new Column's AutoIncrement property to true and the column's values will be filled in for you.
HTH
If I understand your question correctly, you are trying to match the row indices of the your DataTable with the sort order indices of your DataGridView. In the example below, the sort column name is "index".
'Apply a sort order to the gridview
table.DefaultView.Sort = "index ASC"
'Assign the datasource of DataGridView to DataTable
gridview.DataSource = table.DefaultView
'Change the index value of the DataTable which will cause
' the DataGridView to resort the view. In this case, swap rows 0 and 1.
table.Rows(0).Item("index") = 1
table.Rows(1).Item("index") = 0
Now the order of the rows in table has not been changed, only the gridview sorts and displays the new order of the rows.
The only way I know of, although it is not a great solution, is as follows:
'Reassign the DataTable to its own sorted DefaultView
table = table.DefaultView.ToTable()
'Reapply a sort order to the gridview
table.DefaultView.Sort = "index ASC"
'Reassign the datasource of DataGridView to DataTable
gridview.DataSource = table.DefaultView
Now both the table and the gridview have the same row order.
Please post a better solution if you know of one. Hope this helps.
I was working my butt off to avoid using databinding on a datagridview. now that I've figured that stuff out this isn't really a problem.
I still feel the datagridview should automatically have a sourceindex property for each datarow, but with
- databinding
- a layer of business objects in between the db and the datagrid
- System.ComponentModel.Browsable(false) attribute
I can make the datagridviewRow hold a reference to the entire object itself, without it showing as a dataGridViewColumn