使用文本框将新行添加到DataGridView

本文关键字:添加 DataGridView 新行 文本 | 更新日期: 2023-09-27 18:20:01

我正在尝试从文本框添加到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

以下是我的建议,现在我知道您确实在表单项目中。我看到另一个人已经提出了这个建议,我正在添加断言,这样如果任何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 });
}

假设您正确设置了DataGridView列,则可以使用以下DataGridViewRowCollection.Add Method(Object[])重载,如以下

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;

您可以从文本框创建一个字符串数组,并将其添加到数据网格视图中。

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