How to browse a dataGridView and store the values in a List or Array

Asked

Viewed 1,749 times

2

I have to enter some data into a datagridView and then need to recover these values and store in a List or Array, so that then I can send it to the database. Guys, I don’t know how to do this! If you gentlemen can help me, I’d be grateful!

Follow an excerpt of the code I’m testing, unsuccessfully..

Note. I can already insert the data with this code below:

private void Form1_Load(object sender, EventArgs e)
        {
            dataGridView1.ColumnCount = 3;
        //Informo os nomes das colunas do dataGridView
        dataGridView1.Columns[0].Name = "Nome";
        dataGridView1.Columns[1].Name = "E-mail";
        dataGridView1.Columns[2].Name = "Telefone";
    }

    private void Button1_Click(object sender, EventArgs e)
    {
        dataGridView1.Rows.Add(textBox1.Text, textBox2.Text, textBox3.Text);
        //limpo os controles
        textBox1.Text = String.Empty;
        textBox2.Text = String.Empty;
        textBox3.Text = String.Empty;
    }

    private void Button2_Click(object sender, EventArgs e)
    {

        foreach (DataGridViewRow dataGridViewRow in dataGridView1.Rows)
        {
           ??
        }
    }

2 answers

1

First of all you have to create an elementary structure to receive your data. In this example I created a struct calling for Individuocontaining three fields nome, email and telefone. For this struct also created a constructor that accepts three arguments and that with these arguments fills the data structure fields.

Immediately afterwards I declared a list called Contato list for the purpose of receiving data from its component dataGridView1.

At the end I modified your method Button2_Clickadding code to fill the list of Contatos with the information of each Individuo with the information obtained from your dataGridView1:

//Estrutura que modela um único individuo
private struct Individuo
{
   String nome;
   String email;
   String telefone;

   public Individuo(String _nome, String _email, String _telefone)
   {
      nome = _nome;
      email = _email;
      telefone = _telefone;
   }
}

//Lista que receberá os dados
List<Individuo> Contatos= new List<Individuo>();

private void Form1_Load(object sender, EventArgs e)
{
    dataGridView1.ColumnCount = 3;
    //Informo os nomes das colunas do dataGridView
    dataGridView1.Columns[0].Name = "Nome";
    dataGridView1.Columns[1].Name = "E-mail";
    dataGridView1.Columns[2].Name = "Telefone";
}

private void Button1_Click(object sender, EventArgs e)
{
    dataGridView1.Rows.Add(textBox1.Text, textBox2.Text, textBox3.Text);
    //limpo os controles
    textBox1.Text = String.Empty;
    textBox2.Text = String.Empty;
    textBox3.Text = String.Empty;
}

private void Button2_Click(object sender, EventArgs e)
{

    //Código para preencher a lista de Contatos com as informações de cada Individuo com as informações obtidas de seu dataGridView1
    foreach (DataGridViewRow dataGridViewRow in dataGridView1.Rows)
    {
       Contatos.Add(
           new Individuo(dataGridViewRow.Cells["Nome"].Value.ToString(), 
                         dataGridViewRow.Cells["E-mail"].Value.ToString(), 
                         dataGridViewRow.Cells["Telefone"].Value.ToString()
                         )
                    );  
    }
}
  • 1

    Very good!! I did the tests and it worked!! Thank you Augusto! Augusto, you could explain how I can take these values that are in the individual variables to pass to the bank.. Usually I do it like this: string Resp = ""; Resp = Ncontato.Insert(_name, _email, _phone); ...// but I’m not getting it!

  • @Phil: I don’t know if this is what you asked for but it must be something like :foreach (Individuo ind in Contatos) { resp = NContato.Inserir(ind.nome, ind.email, ind.telefone); }

  • I did as you suggested, but he still does not see the variables name, email and phone... I will continue searching here! Thanks @Augusto

  • Good research, but anything open a specific question about database showing code within NContato.Inserir.

  • Ncontato is a class with the insert method, which in this case is to receive the values of these variables name, email.... Valeu @Augusto!!

0


Greetings.

You can use the for in place of foreach to walk the DataGridView and take the data through the cell indices of each row.

//percorre o DataGridView
   for (Int32 i = 0; i < dgwMeuDataGridView.Rows.Count; i++)
      {
          meuList.add = dgwMeuDataGridView.Rows[i].Cells[0].Value.ToString();// coluna 1
          meuList.add = dgwMeuDataGridView.Rows[i].Cells[1].Value.ToString();// coluna 2
          meuList.add = dgwMeuDataGridView.Rows[i].Cells[1].Value.ToString();// coluna 3
      }
  • Hi, Agnaldo, hello, Agnaldo! I did as you suggested, and after going through the dataGridView the program returns the following error: System.Nullreferenceexception 'Object Reference not set to instance of an Object. ' System.Windows.Forms.DataGridViewCell.Value.get returned null

  • Whoa, whoa, all right? The error occurs because the way you are filling Datagridview the last line of it is always empty and trying to add this empty line to your List will actually give error. One solution is: <pre> for (Int32 i = 0; i < dgwMeuDataGridView.Rows.Count-1; i++) {...}</pre> .

  • for (Int32 i = 0; i < dgwMeuDataGridView.Rows.Count -1; i++)

  • Of course, if somehow a Datagridview line becomes empty it will generate error by capturing this empty line for your List. The ideal is to do validation to not pick up line with empty content or allow no empty line when filling Datagridview. I hope I helped.

  • yes, yes.. then when I came across this mistake I did some more research and found exactly what you said there.. Thanks again @Agnaldo

  • I am happy to have helped. if it was helpful mark as answer to rank and help other people who are with this same doubt, hug

Show 1 more comment

Browser other questions tagged

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