Hi John,
The code I provided in my first reply is used to get the value of the
primary key of the current row of a DataGrid, not of the selected row. And
the VB.Net version of my sample code is below.
// Option 1 to get the current row
Dim row As DataRowView = CType(Me.BindingContext(Me.dataset11,
"City").Current, DataRowView)
Dim keyvalue As Object = row(Me.dataset11.City.PrimaryKey(0).ColumnName)
In the above sample, I make use of the CurrencyManager object associated
with the dataset11 to get the current row. I could always get the correct
current row by option 1 even after I sort the DataGrid, i.e by clicking on
the the DataGrid's column headers.
In fact, I could also use the CurrentRowIndex property of the DataGrid to
get the current row. The following is a sample.
// Option 2 to get the current row
Dim row As DataRow = Me.dataset11.City.Rows(Me.DataGrid1.CurrentRowIndex)
However, if I sort the DataGrid, the indexes of the records in the DataGrid
aren't consistent to that in the DataTable. Thus, in this case, I couldn't
get the correct current row by option 2.
The only problem I'm haveing is, it doesn't matter what row I select, I
only seem to get data from the first row. Any idea why?
What I want to point out is that the selected row of a DataGrid is not
equal to the current row. You could select several rows in a DataGrid,
however the current row is the only one indicated by an arrow in the row
header.
Unfortunately, we could not get the selected rows of a DataGrid directly
because there isn't such a property or method of DataGrid to return the
selected rows. The CurrencyManager object doesn't provide such a function
either. But we could call the IsSelected method of DataGrid to determin
which rows are selected. We could store the indexes of the selected rows
into a collection and then get the value of the primary key of each row
indicated in the collection. Below is a sample.
Dim selectedRows As New ArrayList
Dim keyValues as New ArrayList
// firstly, get the index of all the selected rows in the DataGrid into
selectedRows
For i As Integer = 0 To Me.dataset11.City.Rows.Count - 1
If Me.DataGrid1.IsSelected(i) Then
selectedRows.Add(i)
End If
Next
// secondly, get the value of the primary key of each row indicated in the
collection and store it into another collection
For i As Integer = 0 To selectedRows.Count - 1
keyValues.Add(Me.dataset11.City.Item(CType(selectedRows(i),
Int32)).Item(Me.dataset11.City.PrimaryKey(0).ColumnName))
Next
This method has a limitation. If you sort the DataGrid, the indexes of the
records in the DataGrid aren't consistent to that in the DataTable. So we
couldn't get the correct selected rows from the DataTable according to the
collection. I think you may set the AllowSorting property of the DataGrid
to false.
Hope this helps.
If you have anything unclear, please feel free to let me know.
Sincerely,
Linda Liu
Microsoft Online Community Support