`DataGridViewComboBoxCell`返回`null`

时间:2014-12-24 12:20:13

标签: c# .net datagridview

DataGridView的第一个单元格是ComboBox。我在这个专栏中添加成员如下...

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.");
}

但是,即使从null中选择了值,该值也会每次返回ComboBoxCell。此处Cell不是null,但是单元格的值为空。

这有什么问题?

1 个答案:

答案 0 :(得分: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 { }
        }
    }