DataGridView中的Combobox的應用)

來源:互聯網
上載者:User

在WinForm中DataGridView可謂是應用比較多的資料顯示控制項了,DataGridView中可以應用各種控制項,關於這樣的文章網上

已有很多。都是執行個體化一個控制項然後通過DataGridView.Controls.Add()方法繫結控制項。然後通過特定的事伯執行資料繫結與操作。

    這幾天在做項目的時候也也用到的DataGridView控制項,而且需要要DataGridView使用ComboBox來動態顯示資料。查了不少

的資料來完成DataGridView中的ComboBox的資料繫結,多數都是通過嚴設定在WinForm中的表單InitializeComponent()中來設

置ComboBox對象的DataSource、DisplayMember、ValueMember的值來實現資料繫結,可是這樣並不能實現每行不同的資料進

行綁定。在查看MSDN的時候我發現一個對象是DataGridViewComboBoxCell 。MSDN上這樣說的:

DataGridViewComboBoxCell 類是用於顯示下拉式方塊控制項(即組合了列表選擇欄位的編輯欄位)的 DataGridViewCell 的專用類型。

當前選定的 DataGridViewComboBoxCell 承載一個 DataGridViewComboBoxEditingControl,使用者可在其中更改儲存格的值

(假設儲存格的 ReadOnly 屬性設定為 false)。 與 ComboBox 控制項不同,DataGridViewComboBoxCell 沒有 SelectedIndex

和 SelectedValue 屬性,而是通過從下拉式清單中選擇值來設定儲存格的 Value 屬性。

所以我這樣實現的:

在DataGridView進行資料繫結時通過for來迴圈添加行(通過DataSource來實現的時候下的的功能無法完成),同時

DataGridViewComboBoxColumn列中填充Null。 然後在DataGridView的RowsAdded事件中添加ComboBox的資料繫結代碼。

 

1       private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
2        {
3            
4            DataGridViewComboBoxCell DgvCell = this.dataGridView1.Rows[e.RowIndex].Cells[1] as DataGridViewComboBoxCell;
5            DgvCell.DataSource = DataSource;
6            DgvCell.DisplayMember = "MeasureName";
7            DgvCell.ValueMember = "MeasureId";
8         }

這樣就可以完成資料繫結了。我們就可以在DataGridVie一行的後面添加一個按鈕列,然後選擇DataGridView的CellClick事件中編寫代碼。

我們可以通過

    

 

string selectValue =(string)(this.dataGridView1.Rows[e.RowIndex].Cells[1] as DataGridViewComboBoxCell).Value;//取得所選值的key即綁定ValueMember的值。
MessageBox.Show("" + selectValue.ToString() + "");

       注意的地方就是如果綁定的的是泛型集合,那麼DisplayMember與ValueMember的值必須是屬性(property)

不可以是類的欄位(Filed)。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.