2

I am trying to Add from textboxes to datagridview but the code doesn't work

dataGridView1.Rows[0].Cells[0].Value = textBox6.Text;
dataGridView1.Rows[0].Cells[1].Value = textBox5.Text;
dataGridView1.Rows[0].Cells[2].Value = textBox7.Text;
dataGridView1.Rows[0].Cells[3].Value = dateTimePicker3.Value;
3
  • there is a button under the textboxes I want to create a new row when the button pressed, there is no code Commented Nov 1, 2015 at 12:43
  • OMG, I did not pay attention to this confusion, by mistake I mixed two question together, sorry for that, now I update it. Commented Nov 1, 2015 at 13:03
  • 1
    Dear Rama, You can review answers and choose accepted answer and also vote for other answers if they are helpful, this way your question and answers will be more helpful for future readers :) Even If you find your answer yourself, I recommend reviewing posted answers. Also If you find a better answer you can post it here. Commented Nov 1, 2015 at 19:32

3 Answers 3

2

Here is what I would suggest now knowing that you are indeed in a forms project. I see another person has suggested this already, I am adding in assertion so that if any of the TextBox controls are empty the row is not added.

if ((!string.IsNullOrWhiteSpace(textBox6.Text)) || (!!string.IsNullOrWhiteSpace(textBox5.Text)) || (!string.IsNullOrWhiteSpace(textBox7.Text)))
{
    dataGridView1.Rows.Add(new object[] {textBox6.Text,textBox5.Text,textBox7.Text,dateTimePicker3.Value });
}
Sign up to request clarification or add additional context in comments.

Comments

2

Assuming you have setup correctly your DataGridView columns, you can use the following DataGridViewRowCollection.Add Method (Object[]) overload like this

dataGridView1.Rows.Add(textBox6.Text, textBox5.Text, textBox7.Text, dateTimePicker3.Value);  

Note that the above will work only if the count of the columns in the grid view is the same as the count of the passed values.

Alternatively you can use something like this, which would work for every scenario

int rowIndex = dataGridView1.Rows.Add();
var row = dataGridView1.Rows[rowIndex];
row.Cells[0].Value = textBox6.Text;
row.Cells[1].Value = textBox5.Text;
row.Cells[2].Value = textBox7.Text;
row.Cells[3].Value = dateTimePicker3.Value;

Comments

1

You can create an array of strings from the textboxes and add this to the datagrid view.

string[] row = new string[] { textBox6.Text,textBox5.Text,textBox7.Text,
           dateTimePicker3.Value};
dataGridView1.Rows.Add(row);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.