Get currently selected row in datagrid?

  • Thread starter Thread starter Chris Ashley
  • Start date Start date
C

Chris Ashley

I have a datagrid bound to a dataview. How do I get the currently selected
row programmatically so I can retrieve my primary key?
 
Chris Ashley said:
I have a datagrid bound to a dataview. How do I get the currently selected
row programmatically so I can retrieve my primary key?

I managed to do this by having my primary key as a 0 width column in my
datagrid tablestyles collection then using the following code:

Dim PKCell As String
PKCell = DataGrid1.Item(DataGrid1.CurrentRowIndex, 4)

Index 4 being my hidden cell... I guess this is bad practice but couldn't
find any other way of doing it.
 
Hi Chris,

This isn't really necessary. What you usually do is this: find the row which
is the currently selected in a control. You could use the Binding Manager to
find out the current
object/row that the bound datagrid is now referring to. For example, to get
the current row, use:
((CurrencyManager)BindingContext[datatablename]).Current.
Cast this into a datarow (or your typed one), and then use it.
Once you have the row, you could get the primary key or whatever field you
require.

Your method will work, but it not the .NET way of doing things :)

This is a good article which explains the data binding procedure in windows
forms:
http://msdn.microsoft.com/library/en-us/dndotnet/html/databindingadonet.asp

HTH,
Rakesh Rajan
 
Back
Top