DataGrid: sorting and current row

D

Dennis McCarthy

I have a DataGrid that is bound to a DataTable in a typed
DataSet. The following code is used to get the current
row in the DataGrid, even after the user has clicked on a
column header to sort:

BindingManagerBase bm = this.dataGrid1.BindingContext
[this.dataGrid1.DataSource, this.dataGrid1.DataMember];
DataRow dr = ((DataRowView)bm.Current).Row;

I would like to have the DataGrid initially be sorted,
just as if the user had clicked on the first column
header. I tried doing this by binding the DataGrid to
sorted DataView.

DataView view = new DataView (MyDataSet.MyDataTable);
view.Sort = "NAME";
dataGrid1.DataSource = view;

This works for sorting, but breaks the logic above for
getting the current row. No matter what row the user
selects, the binding manager always has the same current
row.

How can I pre-sort my DataGrid without losing the ability
to track the current row?

Thanks,
Dennis
 
D

Dmitriy Lapshin

Dennis,

At the first glance I can see nothing wrong with the source code provided.
BindingManagerBase bm = this.dataGrid1.BindingContext
[this.dataGrid1.DataSource, this.dataGrid1.DataMember];
DataRow dr = ((DataRowView)bm.Current).Row;

The only thing that probably needs to be clarified is that CURRENT ROW and
SELECTED ROW are not the same. There can be multiple selected rows
(highlighted in blue color by default), but only one current row (indicated
with a small filled triangle icon in the row header).

bm.Current will return the CURRENT ROW, and CurrentRowIndex will reflect its
index in the grid. Why I am stressing on this difference is because you have
mentioned a "selection" and I am not sure what exactly do you mean here. I
know very well how confusing DataGrid behaviour can be, so I mean absolutely
no offense, just trying to understand where the problem actually can hide.

--
Dmitriy Lapshin [C# / .NET MVP]
X-Unity Unit Testing and Integration Environment
http://x-unity.miik.com.ua
Deliver reliable .NET software

Dennis McCarthy said:
Dmitriy,

The code that gets the current row for the data grid:

BindingManagerBase bm = this.dataGrid1.BindingContext
[this.dataGrid1.DataSource, this.dataGrid1.DataMember];
DataRow dr = ((DataRowView)bm.Current).Row;

executes in the event handler for a menu item. The data
set has been populated and the data grid bound before the
user selects the menu item.

I hope that helps.

Dennis
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top