C# DataGridView添加新行的2個(gè)方法
可以靜態(tài)綁定數(shù)據(jù)源,這樣就自動(dòng)為DataGridView控件添加 相應(yīng)的行。假如需要?jiǎng)討B(tài)為DataGridView控件添加新行,方法有很多種,下面簡(jiǎn)單介紹如何為DataGridView控件動(dòng)態(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ù)返回添加新行的索引號(hào),即新行的行號(hào),然后可以通過該索引號(hào)操作該行的各個(gè)單元格,如dataGridView1.Rows[index].Cells[0].Value = "1"。這是很常用也是很簡(jiǎn)單的方法。
方法二:
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);
方法二比方法一要復(fù)雜一些,但是在一些特殊場(chǎng)合非常實(shí)用,例如,要在新行中的某些單元格添加下拉框、按鈕之類的控件時(shí),該方法很有幫助。
DataGridViewRow row = new DataGridViewRow(); 是創(chuàng)建DataGridView的行對(duì)象,DataGridViewTextBoxCell是單元格的內(nèi)容是個(gè) TextBox,DataGridViewComboBoxCell是單元格的內(nèi)容是下拉列表框,同理可知,DataGridViewButtonCell是單元格的內(nèi)容是個(gè)按鈕,等等。textboxcell是新創(chuàng)建的單元格的對(duì)象,可以為該對(duì)象添加其屬性。然后通過row.Cells.Add(textboxcell)為row對(duì)象添加textboxcell單元格。要添加其他的單元格,用同樣的方法即可。
最后通過dataGridView1.Rows.Add(row)為dataGridView1控件添加新的行row。
相關(guān)文章
詳解C#如何使用屏障實(shí)現(xiàn)多線程并發(fā)操作保持同步
這篇文章主要為大家詳細(xì)介紹了C#如何使用屏障實(shí)現(xiàn)多線程并發(fā)操作保持同步,文中的示例代碼簡(jiǎn)潔易懂,具有一定的借鑒價(jià)值,有需要的小伙伴可以參考下2024-01-01
C#判斷一個(gè)字符串是否是數(shù)字或者含有某個(gè)數(shù)字的方法
這篇文章主要介紹了C#判斷一個(gè)字符串是否是數(shù)字或者含有某個(gè)數(shù)字的方法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-06-06
詳解WPF如何在基礎(chǔ)控件上顯示Loading等待動(dòng)畫
這篇文章主要為大家詳細(xì)介紹了WPF如何在基礎(chǔ)控件上顯示Loading等待動(dòng)畫的效果,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價(jià)值,需要的可以參考一下2023-04-04
c#發(fā)送請(qǐng)求訪問外部接口的實(shí)例
這篇文章主要介紹了c#發(fā)送請(qǐng)求訪問外部接口的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-01-01

