Datagridview windows Forms

Asked

Viewed 430 times

2

I have the following question: I have one Grid which 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 type variable int and write to the database. I only need the selected Ids to be saved to the database.

Renan My question is the following how to assign these ids to an instance of class because the following error appears even after the suggestions "Object reference not defined for an instance of an object"inserir a descrição da imagem aqui.

  • And what is the question/doubt? You posted only what you need to do.

  • Apparently my answer didn’t solve your problem, so try posting your code so it’s easier so we can help you. Apparently by the image you’re not instantiated fomarsemestre before using it, so it gives Nullreferenceexception, adjust your question in more detail.

1 answer

3


You can use the property Selectedrows of your Datagridview and take the cell referring to Id, something like that:

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 to work you need to select the entire line.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.