无法在可编辑组合框中获取输入文本

4
在我的DataGridView中,我有一个文本框列和一个可编辑的组合框列在Winforms中。但是,当我在组合框文本框中输入新值并按下回车键时,我没有得到所键入的值作为相应单元格的值。请问有谁能帮忙解决这个问题?
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;
            }
        }
    }
}

1
我不能确定你正在做的事情会发生什么,但我知道绑定的下拉框列必须对每一行使用相同的数据源。我认为这对你来说行不通。你可以使用另一种机制,例如弹出模态选择列表。 - Crowcoder
1个回答

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;
    }

在GitHub上找到列为组合框的表的完整源代码

希望这可以帮助你。


1
感谢您留下的建议。但这并不能解决我的问题。 - Greeshma R
1
然后请编辑您的问题并更详细地解释您的问题。 - Baltasarq
我已经将我的组合框设置为可编辑,但是我无法获取输入在组合框文本中的值,以便我可以保存。 - Greeshma R
我刚学到,要想获取此组合框的选定索引,需要监听 SelectedIndexChanged 事件。 - Baltasarq
已经更新了Github和答案,请看是否解决了问题。 - Baltasarq
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接