【问题标题】:Not getting the typed text in editable combobox未在可编辑组合框中获取键入的文本
【发布时间】:2018-09-13 23:27:20
【问题描述】:

在我的 datagridview 中,我在 winforms 中有一个 textboxcolumn 和一个可编辑的组合框列。但是在组合框文本中键入新值并按 Enter 键时,我没有将键入的值作为相应的单元格值。有人可以请帮助解决这个问题。

private void dgv_customAttributes_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{

    DataGridViewRow row = dgv_customAttributes.CurrentRow;           
    if (row.Cells[1].Value.ToString() != null)
    {
        //Here the selectedVal is giving the old value instead of the new typed text
        string SelectedVal = row.Cells[1].Value.ToString();
        foreach (CustomAttribute attribute in customAttributes)
        {
            if (row.Cells[0].Value.ToString() == attribute.AttributeName)
            {
                attribute.AttributeValue = SelectedVal;
                break;
            }
        }
    }
}

【问题讨论】:

  • 我不能说我确切地知道你正在做的事情会发生什么,但我知道绑定的组合框列的每一行必须具有相同的数据源。我不认为这对你有用。你可能会使用不同的机制,比如弹出一个模态选择列表。

标签: c#


【解决方案1】:

您需要在组合框显示时找出组合框,并在所选索引更改时为其附加一个事件处理程序(因为无法从列或单元格本身获取该信息)。

不幸的是,这意味着捕获事件 CellEndEdit 是没有用的。

在下面的示例中,文本框会填充所选选项,但您可以执行任何其他操作,例如在枚举变量中选择特定值或其他任何操作。

    void OnEditingControlShowing(DataGridViewEditingControlShowingEventArgs e)
    {
        if ( e.Control is ComboBox comboEdited ) {
            // Can also be set in the column, globally for all combo boxes
            comboEdited.DataSource = ListBoxItems;
            comboEdited.AutoCompleteMode = AutoCompleteMode.Append;
            comboEdited.AutoCompleteSource = AutoCompleteSource.ListItems;

            // Attach event handler
            comboEdited.SelectedValueChanged +=
                (sender, evt) => this.OnComboSelectedValueChanged( sender );
        }

        return;
    }

    void OnComboSelectedValueChanged(object sender)
    {
        string selectedValue;
        ComboBox comboBox = (ComboBox) sender;
        int selectedIndex = comboBox.SelectedIndex;

        if ( selectedIndex >= 0 ) {
            selectedValue = ListBoxItems[ selectedIndex ];
        } else {
            selectedValue = comboBox.Text;
        }

        this.Form.EdSelected.Text = selectedValue;
    }

找到complete source code for the table in which a column is a combobox in GitHub

希望这会有所帮助。

【讨论】:

  • 感谢您留下您的建议。但这并不能解决我的问题
  • 那么请编辑您的问题并更详细地解释您的问题。
  • 我已经让我的组合框也可以编辑了,但是我无法获取组合框文本中输入的值,所以我可以保存。
  • 我刚刚了解到,要获取此组合框的选定索引,您需要收听SelectedIndexChangedevent。
  • 我已经更新了答案,因为解决方案完全在别处。
猜你喜欢
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-18
  • 2012-05-16
  • 2018-01-08
相关资源
最近更新 更多