2011/12/05

Get Any Cell Value from a selected row/cell In .NET

Sometimes in your application you need to do a very simple thing like selecting a row in a datagrid to get a cell value, but in .NET's DataGridView will highlight the cell when you click on it and not the row or column.

So why do you have to select a whole row to get a value, or why do you have to select the exact cell i want?
there is a very simple code that accepts any selected cell/row to get your needed cell in that row - check the image:
as you can see I clicked on "Mataderos 2312" cell and got the result "ANTON" which is the value I want, without the need of selecting the whole row or selecting the exact cell needed, just any cell in that row.
code:

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim str As String = DataGridView1.Rows(DataGridView1.SelectedCells.Item(0).RowIndex).Cells(0).Value
TextBox1.Text = str
End Sub


code description:
to get the selected item:
DataGridView1.SelectedCells.Item(0).Value
to get it's row index
DataGridView1.SelectedCells.Item(0).RowIndex
to get a cell for it's row
DataGridView1.Rows(DataGridView1.SelectedCells.Item(0).RowIndex).Cells(0).Value

ليست هناك تعليقات: