Reputation: 134
Hello everybody and thanks in advance for taking the time to read my question.
This is my scenario:
I have a DataGridView
were I display some values from a table with a PK Id
. I don't want to display the Id
field, but still to be able to Access the value into Id
to perform a DELETE
statement on my database.
I have hidden that Id
field with the instruction: DataGridView.Columns("Id").Visible = False
The Id
field is the first on the DataGridView, so it gets the index 0 when it is selected.
If I try to get its value trough DataGrid.SelectedCells.Item(0).Value
the program throws an exception.
I have tested the same code without using DataGridView.Columns("Id").Visible = False
and it works perfectly, so I asume that the function DataGrid.SelectedCells.Item(0).Value
can't work if the field that corresponds to Item(0)
is not visible.
I need to select the Id
directly from the DataGridView
since its Id
variates with each row.
Any different approach to this issue would be appreciated.
Upvotes: 0
Views: 109
Reputation: 91
You can use .Tag in a row to store information instead of a hidden column.
For example:
DataGridView1.Rows(sID).Tag = Your id.
Upvotes: 0
Reputation: 41
Try this
If Not IsNothing(DataGrid.CurrentRow) Then
Dim intId As Integer = DataGrid.CurrentRow.Cells("Id").Value
End If
Upvotes: 0
Reputation: 54417
There's no need to hide columns or refer to the grid at all in code. Start by adding the columns you do want to the grid in the designer. Set the DataPropertyName
of each column to tell it which data source column to bind to.
In code, use an OleDbDataAdapter
to populate a DataTable
and then bind that to the grid via a BindingSource
. Whenever you want to delete the current record, call RemoveCurrent
on the BindingSource
. That will flag the row as Deleted
and hide it from the UI.
Once you've made all the changes you want to make, call Update
on the same data adapter to save the changes from the DataTable
back to the database in a batch.
Upvotes: 1