可以靜態繫結資料來源,這樣就自動為DataGridView控制項添加 相應的行。假如需要動態為DataGridView控制項添加新行,方法有很多種,下面簡單介紹如何為DataGridView控制項動態添加新行的兩種方 法:
方法一:
複製代碼 代碼如下: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"。這是很常用也是很簡單的方法。
方法二:
複製代碼 代碼如下: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。