DataGridView windows Forms

2

I have the following question: I have Grid that is composed of various information (id, city, zip code) and the user will select several lines in this Grid . I need to capture the selected codes, assign these IDs to a variable of type int and write to the database. I need only the IDs selected to be saved in the database.

Renan My question is the following how to assign these ids to a class instance because I'm aware of the following error even after the suggestions "Object reference not set to an instance of an object" .

    
asked by anonymous 24.02.2015 / 05:03

1 answer

3

You can use the SelectedRows of your DataGridView and get the cell for the Id, something like this:

In C #

int id = 0;
foreach (DataGridViewRow linha in dataGridView.SelectedRows)
{
    // nesse caso o cast só irá funcionar se o tipo de dado
    // que está na coluna for do tipo int, caso contrário
    // utilize Convert.ToInt32, por exemplo
    id = (int) linha.Cells["Id"].Value;

    // faz o que você precisa com o id
}

In VB

 
Dim id As Integer
For Each linha As DataGridViewRow In dataGridView.SelectedRows
    ' nesse caso o DirectCast só irá funcionar se o tipo de dado
    ' que está na coluna for do tipo Integer, caso contrário
    ' utilize CType, por exemplo
    id = DirectCast(linha.Cells("Id").Value, Integer)

    '  faz o que você precisa com o id
Next

Note that in order to work, you must select the entire line.

    
24.02.2015 / 11:54