C# DataGridView添加新行的2個方法

來源:互聯網
上載者:User

可以靜態繫結資料來源,這樣就自動為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。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.