C# DataGridView控件基本操作
![一根胡萝卜](https://pica.zhimg.com/v2-14c93c0e5762ff34e6acfc8f401889cd_l.jpg?source=172ae18b)
![](https://pic1.zhimg.com/v2-4812630bc27d642f7cafcd6cdeca3d7a.jpg?source=88ceefae)
DataGridView添加新行
1.可以静态绑定数据源,这样就自动为DataGridView控件添加 相应的行。
2.动态为DataGridView控件添加新行方法一:
int row1 =this.dataGridView1.Rows.Add();
this.dataGridView1.Rows[row1 ].Cells[0].Value = "1";
this.dataGridView1.Rows[row1 ].Cells[1].Value = "2";
this.dataGridView1.Rows[row1 ].Cells[2].Value = "3";
3.动态为DataGridView控件添加新行方法二:
利用dataGridView1.Rows.Add()事件为DataGridView控件增加新的行,该函数返回添加新行的索引号,即新行的行号,然后可以通过该索引号操作该行的各个单元格,如dataGridView1.Rows[row1].Cells[0].Value = "1"。这是很常用也是很简单的方法。
DataGridViewRow row1 = new DataGridViewRow();
dataGridView1.Rows.Add(row1);
但是不能通过循环调用添加新行,否则会报错提示该行已经加入。
DataGridViewRow row1 = new DataGridViewRow();
for (int i = 0; i < 10; i++)
dataGridView1.Rows.Add(row);
目前通过这种方法添加多个行,很笨重,有更好的方法可以交流下
DataGridViewRow row0 = new DataGridViewRow();
dataGridView1.Rows.Add(row0);
DataGridViewRow row1 = new DataGridViewRow();
dataGridView1.Rows.Add(row1);
DataGridViewRow row2 = new DataGridViewRow();
dataGridView1.Rows.Add(row2);
DataGridViewRow row3 = new DataGridViewRow();
dataGridView1.Rows.Add(row3);
DataGridViewRow row4 = new DataGridViewRow();
dataGridView1.Rows.Add(row4);
DataGridViewRow row5 = new DataGridViewRow();
dataGridView1.Rows.Add(row5);
DataGridViewRow row6 = new DataGridViewRow();
dataGridView1.Rows.Add(row6);
DataGridViewRow row7 = new DataGridViewRow();
dataGridView1.Rows.Add(row7);
DataGridViewRow row8 = new DataGridViewRow();
dataGridView1.Rows.Add(row8);
DataGridViewRow row9 = new DataGridViewRow();
dataGridView1.Rows.Add(row9);
方法三:
DataGridViewRow row = new DataGridViewRow();
DataGridViewTextBoxCell textboxcell = new DataGridViewTextBoxCell();
textboxcell.Value = "aaa";
row.Cells.Add(textboxcell);
DataGridViewComboBoxCell comboxcell = new DataGridViewComboBoxCell();
row.Cells.Add(comboxcell); dataGridView1.Rows.Add(row);
方法二比方法一要复杂一些,但是在一些特殊场合非常实用,例如,要在新行中的某些单元格添加下拉框、按钮之类的控件时,该方法很有帮助。
DataGridViewRow row = new DataGridViewRow(); 是创建DataGridView的行对象,DataGridViewTextBoxCell是单元格的内容是个 TextBox,DataGridViewComboBoxCell是单元格的内容是下拉列表框,同理可知,DataGridViewButtonCell是单元格的内容是个按钮,等等。textboxcell是新创建的单元格的对象,可以为该对象添加其属性。然后通过row.Cells.Add(textboxcell)为row对象添加textboxcell单元格。要添加其他的单元格,用同样的方法即可。
最后通过dataGridView1.Rows.Add(row)为dataGridView1控件添加新的行row。
DataGridView不显示最下面的新行
通常 DataGridView 的最下面一行是用户新追加的行(行头显示 * )。如果不想让用户新追加行即不想显示该新行,可以将 DataGridView 对象的 AllowUserToAddRows 属性设置为 False。DataGridView1.AllowUserToAddRows = false;但是,可以通过程序: DataGridViewRowCollection.Add 为 DataGridView 追加新行。
为生成的新行添加默认值
当用户选择“新行”作为当前行,DataGridView会触发DefaultValuesNeeded事件。在该事件中可以访问新行,并为其生成默认值,为用户输入提供方便。
private void dataGridView1_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
e.Row.Cells["Region"].Value = "WA";