【问题标题】:DataGridView ComboBox doesn't save when focus焦点时DataGridView ComboBox不保存
【发布时间】:2011-09-28 08:01:37
【问题描述】:

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

【问题讨论】:

  • 通常当你点击按钮时它会获得焦点,我认为还有其他东西可以展示你是如何做到这一点的?

标签: c# datagridview focus datagridviewcombobox


【解决方案1】:

很奇怪。我最近这样做了,它就像一个魅力。在我的应用程序中,当 gridview 处于编辑模式(只读 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

抱歉,忘了告诉你最重要的事情,即使专注,它也有效。 如果您正在寻找其他东西,请在我头上扔石头。 希望对您有所帮助。

【讨论】:

    【解决方案2】:

    在保存之前尝试调用UpdateSource

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

    HTH

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-14
      • 1970-01-01
      • 1970-01-01
      • 2012-03-15
      相关资源
      最近更新 更多