Add values from textBox to dataGridView C#

DataGridView Control:
            Datagridview is the one of the efficient control in C#.The DataGridView displays the contents of a data source. It is a control in Windows Forms that uses a grid format. Inserting the values from textbox to datagridview control is easiest way. For that first you have to add one windows form.Add atagridview control,five textboxes and one button to the form or webpage.Add five columns to the datagridview control statically and namethe columns as name,class,city,phone and zipcode. Click here for more information about datagridview control.



Event :- This code should write in button_Click event.


dataGridView1.Rows[0].Cells[0].Value = textBox1.Text;
dataGridView1.Rows[0].Cells[1].Value = textBox2.Text;
dataGridView1.Rows[0].Cells[2].Value = textBox3.Text;
dataGridView1.Rows[0].Cells[3].Value = textBox4.Text;
dataGridView1.Rows[0].Cells[4].Value = textBox5.Text;


This is one way to add values from textbox to datagridview. The another way is to
assign the columns names instead of cell index number.For that the code will be like bellow

dataGridView1.Rows[0].Cells["name"].Value = textBox1.Text;
dataGridView1.Rows[0].Cells["class"].Value = textBox2.Text;
dataGridView1.Rows[0].Cells["city"].Value = textBox3.Text;
dataGridView1.Rows[0].Cells["phone"].Value = textBox4.Text;
dataGridView1.Rows[0].Cells["zipcode"].Value = textBox5.Text;

           

I hope this code will help you.

7 comments:

  1. Sir,
    how can i do this dynamically?

    ReplyDelete
    Replies
    1. int row = 0;
      dataGridView1.Rows.Add();
      row = dataGridView1.Rows.Count - 2;
      dataGridView1["Column1", row].Value = textBox1.Text;
      dataGridView1["Column2", row].Value = textBox2.Text;
      dataGridView1["Column3", row].Value = textBox3.Text;
      dataGridView1["Column4", row].Value = textBox4.Text;
      dataGridView1["Column5", row].Value = textBox5.Text;
      dataGridView1.Refresh();

      Delete
    2. can this be done without clickbutton? I mean, after typing and moving to the next text box, datagridview will capture the text automatically. thanks

      Delete
  2. Thank you so much for this, it was really helpful.

    ReplyDelete
  3. This works easy and perfect for me though.
    go to your designer textbox of which you would like to display the values as you type, in dataGridView. Right click the textbox, go to property section click on event section and locate KEYUP then double click and type this code.

    dataGridView1.RowCount = 1;
    if (textbox1.Text.Length > 0)
    {
    dataGridView1.Rows[0].Cells[1].Value = textbox1.Text;
    }
    else
    {
    dataGridView1.Rows[0].Cells[1].Value = "";
    }

    else you can use this .

    dataGridView1.Rows[0].HeaderCell.Value = textbox1.Text;

    ReplyDelete