DataGridView ComboBox在焦点时不保存

时间:2011-09-28 08:01:37

标签: c# datagridview focus datagridviewcombobox

在DataGridView ComboBox中选择一个值并单击bindingnavigator中的保存按钮后,数据不会在数据库中获得更新。用户必须失去焦点才能更新数据。有没有办法解决这个问题?

2 个答案:

答案 0 :(得分:1)

怪异。我最近做了这件事,它就像一个魅力。在我的应用程序中,当gridview处于编辑模式时(Readonly false),当你选择单元格时,它将成为组合框,当你离开单元格时,它将表现为文本框。这就是我做的事情

void dgUpdateItems_CellEnter(object sender, DataGridViewCellEventArgs e)
{
    DataGridView dg = (DataGridView)sender;
    if (e.ColumnIndex == dg.Columns["ItemCategory"].Index)
    {
        if (e.ColumnIndex == e.RowIndex)
        {
            dg[e.ColumnIndex, e.RowIndex].ReadOnly = true;
            return;
        }
        DataGridViewComboBoxCell cmbCell = new DataGridViewComboBoxCell();
        ComboUpdate(cmbCell);
        cmbCell.Value = ((DataGridView)sender)[e.ColumnIndex, e.RowIndex].Value.ToString();
        ((DataGridView)sender)[e.ColumnIndex, e.RowIndex] = cmbCell;
    }
}

void dgUpdateItems_CellLeave(object sender, DataGridViewCellEventArgs e)
{
    DataGridView dg = (DataGridView)sender;
    if (e.ColumnIndex == dg.Columns["ItemCategory"].Index)
    {
        if (e.ColumnIndex == e.RowIndex)
            return;

        string str = dg[e.ColumnIndex, e.RowIndex].Value.ToString();
        DataGridViewComboBoxCell cmb = (DataGridViewComboBoxCell)dg[e.ColumnIndex, e.RowIndex];
        string val = cmb.Value.ToString();

        dg[e.ColumnIndex, e.RowIndex] = new DataGridViewTextBoxCell();
        dg[e.ColumnIndex, e.RowIndex].Value = val;

如果不理解,这是我的代码的一部分,请告诉我。 这是一个链接检查出来。它可能有所帮助。 ComboBox in DatagridView in Edit Mode

对不起,忘了告诉你最重要的事情,即使重点突出也行不通。 如果你正在寻找别的东西,请在我头上扔一块石头。 希望它有所帮助。

答案 1 :(得分:0)

在保存之前尝试拨打UpdateSource

ComboBox c = Keyboard.FocusedElement as ComboBox;
if ((c != null) && (c.GetBindingExpression(ComboBox.TextProperty) != null))
  c.GetBindingExpression(ComboBox.TextProperty).UpdateSource();

HTH

相关问题