2014-12-24 195 views
0

我的DataGridView的第一個單元格是ComboBox。我加入成員像下面此列...`DataGridViewComboBoxCell`返回`null`

DataTable dt = new DataTable(); 
string qry = "SELECT [NAME] FROM [PERSONS]"; 

// running ExcecuteNonQuery() function in globalData.cs file 
dt = globalData.q.select(qry, globalData.connectionstring); 

foreach (DataRow row in dt.Rows) 
{ 
    (this.dataGrid.Columns["Name"] as DataGridViewComboBoxColumn).Items.Add(row[0].ToString()); 
} 

Cell_Leave事件

if ((this.dataGrid.CurrentRow.Cells[0] as DataGridViewComboBoxCell).Value == null) 
{ 
    MessageBox.Show("You must select one option."); 
} 

檢查,但該值,即使該值從ComboBoxCell選擇每次都返回null。這裏Cell不是null,但單元格的值爲空。

這是怎麼回事?

+0

datagridviewcomboboxcolumn在運行時添加或在'DataGridView'已經添加的datagridview – SK2185

+0

已經添加。 – DhavalR

+0

在表單加載事件中綁定datagridviewcombobox例如:Name .Datasource =「yoursource」; Name.DisplayMember = 「Dispmem」; Name.ValueMember = 「Valuemem」; – SK2185

回答

0

我實現了這個像下面....

private void DataGrid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) 
    { 
     if (this.dataGrid.CurrentCell.ColumnIndex == 0 && e.Control is ComboBox) 
     { 
      ComboBox comboBox = e.Control as ComboBox; 
      comboBox.KeyDown += this.DataGridComboBox_KeyDown; 
     } 
    } 

    private void DataGridComboBox_KeyDown(object sender, KeyEventArgs e) 
    { 
     if (!(e.Control && e.KeyCode == Keys.S) && !(e.Control && e.KeyCode == Keys.C)) 
     { 
      try 
      { 
       var currentcell = this.dataGrid.CurrentCellAddress; 
       var sendingCB = sender as DataGridViewComboBoxEditingControl; 
       DataGridViewComboBoxCell cel = (DataGridViewComboBoxCell)this.dataGrid.Rows[currentcell.Y].Cells[0]; 
       cel.Value = sendingCB.EditingControlFormattedValue.ToString(); 
      } 
      catch { } 
     } 
    }