0

我是新的Windows窗體應用程序開發人員。無法在Visual Studio 2010中找到DataGridViewComboBoxColumn的「SelectedIndex」屬性

我正在使用可編輯網格視圖進行數據輸入。

網格視圖中的一個字段的類型爲ComboBoxColumn。我正在填充代碼中的數據。

我的問題是,如果數據項計數大於0,那麼第一項應被自動選擇。

Page_Load()我的代碼是:

private void Form1_Load(object sender, EventArgs e) 
{ 
    cn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\Study\sem 6\Practice\WindowsFormsApplication1\Practice.accdb"); 
    cn.Open(); 
    cmd = new OleDbCommand("Select * from Grade", cn); 
    da = new OleDbDataAdapter(cmd); 
    ds = new DataSet(); 
    da.Fill(ds); 
    cn.Close(); 
} 

private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) 
{ 
    DataGridViewComboBoxCell cmb = (DataGridViewComboBoxCell)(dataGridView1.Rows[e.RowIndex].Cells[1]); 
    cmb.DataSource = ds.Tables[0]; 
    cmb.DisplayMember = "Grd"; 
    cmb.ValueMember = "ID"; 

    if(cmb.Items.Count > 0) 
    // Here I am not finding the the combo box's SelectedIndex Property. 
} 

請幫助解決這個問題。

在此先感謝。

+0

cmb.SelectedItem。你在找這個嗎? – 2013-04-04 12:56:45

+0

是的,但我既沒有發現'cmb.SelectedItem'也沒有'cmb.SelectedIndex' @FaisalHafeez – 2013-04-04 12:58:14

+0

cmb.Value或cmb.DisplayMember。 – 2013-04-04 13:00:54

回答

0

DataGridViewComboBoxCell沒有這些屬性。看在documentaion

Others已經嘗試了不同的方法。在你的代碼中,它會看起來像這樣:

private ComboBox _chashedComboBox; 

    private void dataGridView1_EditingControlShowing() 
    { 
     _chashedComboBox = e.Control as ComboBox; 
    } 

    private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) 
    { 
      var cmb = _chashedComboBox; 
      if(cmb != null) 
      { 
       cmb.DataSource = ds.Tables[0]; 
       cmb.DisplayMember = "Grd"; 
       cmb.ValueMember = "ID"; 

       if(cmb.Items.Count > 0) 
       cmb.SelectedIndex = 0; 
      } 
    } 
+0

主席先生,我試着按你的答案,但得到錯誤的'dataGridView1_EditingControlShowing()'是無法投類型的對象'DataGridViewTextBoxEditingControl'鍵入'ComboBox' – 2013-04-04 13:27:12

+0

啊哈啊 - SRY,我投錯了。不是每個單元格都包含一個組合框。現在它只會返回null而不是拋出一個錯誤。嘗試一下。 – 2013-04-04 13:30:08

+0

點擊[這裏](http://i.imgur.com/UQTznyK.png)查看錯誤。 – 2013-04-04 13:31:09

相關問題