C# 使用文本框向DataGridView添加新行

C# 使用文本框向DataGridView添加新行,c#,datagridview,C#,Datagridview,我试图将文本框添加到datagridview,但代码不起作用 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.Va

我试图将文本框添加到datagridview,但代码不起作用

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;

假设您正确设置了
DataGridView
列,您可以像这样使用以下重载

dataGridView1.Rows.Add(textBox6.Text, textBox5.Text, textBox7.Text, dateTimePicker3.Value);  
请注意,只有当网格视图中的列数与传递的值数相同时,上述方法才有效

或者,您也可以使用类似的方法,这适用于所有场景

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;

您可以从文本框创建字符串数组,并将其添加到datagrid视图中

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

以下是我现在的建议,因为我知道您确实在一个表单项目中。我看到另一个人已经提出了这一点,我正在添加断言,这样如果任何TextBox控件为空,就不会添加行

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 });
}

文本框下有一个按钮我想在按下按钮时创建一个新行,没有codeOMG,我没有注意到这种混乱,我错误地将两个问题混合在一起,很抱歉,现在我更新它。亲爱的Rama,你可以查看答案并选择接受的答案,如果其他答案有用,也可以投票选择其他答案,通过这种方式,你的问题和答案将对未来的读者更有帮助:)即使你自己找到了答案,我建议你回顾一下发布的答案。如果你找到了更好的答案,你可以把它贴在这里。