Knowledge Required: To understand the following solution you must have knowledge of:
- Typed DataSets
- Data Tables
- DataGridView Control
- Data Binding
- Windows Forms
We use DataGridView Control to display the contents of a DataTable. For this purpose we first bind the DataTable with DataGridView Control using a BindingSource. Sometimes it is required that we need to get the DataTable's Row from DataGridView Row.
For example, we have an event in DataGridView i.e. CellDoubleClick event. This event is triggered whenever the DataGridView Cell is double clicked. In this event we are supplied with an Event Argument of type DataGridViewCellEventArgs which contains 2 Members RowIndex and ColumnIndex.
Suppose we want that whenever the Cell is double clicked in the DataGridView, we extract out that particular row of our DataTable and then perform some action.
To fully understand this consider a Student Table having Student ID, Student Name and lots of other different fields. We have bound this Table with our DataGridView control and in DataGridView control we are only displaying the Student Name. Whenever the Student Name is double clicked we want that another Window should open i.e. Student Detail Window that contains all the Fields of Table. For this purpose we will use the following code:
Private Sub StudentDataGridView_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles StudentDataGridView.CellDoubleClick
Dim drvStudent As DataRowView
Dim rowStudent As StudentDataSet.StudentRow
Dim frmNew As StudentDetailForm
drvStudent = StudentDataGridView.Rows(e.RowIndex).DataBoundItem
rowStudent = drvStudent.Row
frmNew = New StudentDetailForm(rowStudent.Student_ID)
frmNew.ShowDialog()
End Sub
As you can see following code gets the DataRowView which is actually bound with DataGridView Row
drvStudent = StudentDataGridView.Rows(e.RowIndex).DataBoundItem
Then we get the actual DataTable Row as,
drvStudent.Row
2 comments:
All my doubts got cleared here... thanks for the nice post...
Nice solution. I am in doubt whether to use this, or just have the items in the datagridview (like the id field in your example) with the visible property to false.
Post a Comment