Selecting and Unselecting Rows in a DataGrid

  • Thread starter Thread starter Tim Rogers
  • Start date Start date
T

Tim Rogers

I'm trying to allow the user to select a row in a datagrid by right
clicking on it (so that I can select the row and then a context menu is
displayed). In the DataGrid MouseDown event handler, I call HitTest on the
DataGrid (supplying the mouse X and Y positions). If a row is selected
(i.e. the mouse pointer is on a row), then I want to de-select any selected
row, and then select the row that is being right clicked. The hit test is
working, but the selecting and unselecting of rows is not.

1) How do I unselect any selected rows? I have tried to use the DataGrid's
Unselect method (passing in the CurrentRowIndex), but this does not seem to
work. Someone else suggested calling ResetSelection(), but it's a protected
member.

2) How do I select a row? When I use the DataGrid's Select() method, the
row becomes 'highlighted', but not selected. I can verify this by
attempting to select a row via Select(), and then check the DataGrid's
CurrentRowIndex property. It doesn't change, and you can see the effects
visually (i.e. that the row I wanted selected isn't selected).

FYI - In case it matters, I don't have the datagrid bound to a database or
anything like that. I'm am bound to a DataSet object which uses a DataTable
object that I am manipulating dynamically via my code.

Any help would be much appreciated.

Thanks,

Tim Rogers
 
1) If you derive the DataGrid, you can add a public method that calls the
protected ResetSelection method. You can then call your public method from
outside the datagrid. Or, you could use the technique in this FAQ, that
loops through the rows, to find the selected rows, and unselect them.

George Shepherd's Windows Forms FAQ contains an entry entitled:

How do I programmatically determine the selected rows in a datagrid?

Check it out at:
http://www.syncfusion.com/faq/winforms/search/775.asp


2) In addition to using grid.Select to select the row, you can also
explicitly set the current cell so that is synced up with your selected row.

thisdataGrid1.CurrentCell = new DataGridCell(selectedRow, 0);

=============================================
Clay Burch, .NET MVP

Syncfusion, Inc.
visit http://www.syncfusion.com for .NET Essentials
 
what protected ResetSelection method? it doesn't appear in the object
browser or in MSDN (I'm using 1.1 on VS.NET 2003)
 
I just got it from th eonline help.

ms-help://MS.VSCC/MS.MSDNVS/cpref/html/frlrfSystemWindowsFormsDataGridClassR
esetSelectionTopic.htm

========================
Clay Burch, .NET MVP

Visit www.syncfusion.com for the coolest tools
 
Back
Top