C# DataGridView添加新行的2個方法
可以靜態(tài)綁定數(shù)據(jù)源,這樣就自動為DataGridView控件添加 相應的行。假如需要動態(tài)為DataGridView控件添加新行,方法有很多種,下面簡單介紹如何為DataGridView控件動態(tài)添加新行的兩種方 法:
方法一:
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 = "監(jiān)聽";
利用dataGridView1.Rows.Add()事件為DataGridView控件增加新的行,該函數(shù)返回添加新行的索引號,即新行的行號,然后可以通過該索引號操作該行的各個單元格,如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(); 是創(chuàng)建DataGridView的行對象,DataGridViewTextBoxCell是單元格的內(nèi)容是個 TextBox,DataGridViewComboBoxCell是單元格的內(nèi)容是下拉列表框,同理可知,DataGridViewButtonCell是單元格的內(nèi)容是個按鈕,等等。textboxcell是新創(chuàng)建的單元格的對象,可以為該對象添加其屬性。然后通過row.Cells.Add(textboxcell)為row對象添加textboxcell單元格。要添加其他的單元格,用同樣的方法即可。
最后通過dataGridView1.Rows.Add(row)為dataGridView1控件添加新的行row。
相關文章
詳解C#如何使用屏障實現(xiàn)多線程并發(fā)操作保持同步
這篇文章主要為大家詳細介紹了C#如何使用屏障實現(xiàn)多線程并發(fā)操作保持同步,文中的示例代碼簡潔易懂,具有一定的借鑒價值,有需要的小伙伴可以參考下2024-01-01
C#判斷一個字符串是否是數(shù)字或者含有某個數(shù)字的方法
這篇文章主要介紹了C#判斷一個字符串是否是數(shù)字或者含有某個數(shù)字的方法,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2018-06-06

