能够静态绑定数据源,这样就自动为DataGridView控件添加 相应的行。假如须要动态为DataGridView控件添加新行,方法有不少种,下面简单介绍如何为DataGridView控件动态添加新行的两种方 法:函数
方法一:this
int index=this.dataGridView1.Rows.Add(); this.dataGridView1.Rows[index].Cells[0].Value = "1"; this.dataGridView1.Rows[index].Cells[1].Value = "2"; this.dataGridView1.Rows[index].Cells[2].Value = "监听";
利用dataGridView1.Rows.Add()事件为DataGridView控件增长新的行,该函数返回添加新行的索引号,即新行的行号,而后能够经过该索引号操做该行的各个单元格,如dataGridView1.Rows[index].Cells[0].Value = "1"。这是很经常使用也是很简单的方法。spa
方法二:code
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。对象