c# - 未在可编辑组合框中获取键入的文本

标签 c#

在我的 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;
            }
        }
    }
}

最佳答案

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

这意味着,不幸的是,捕获事件 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 .

希望这对您有所帮助。

关于c# - 未在可编辑组合框中获取键入的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52257984/

相关文章:

c# - 使用 Dapper 将列表插入临时表

javascript - 如何在同一 View 的3个不同 View 模型下使用3个不同的数据表?

c# - 使用属性属性在MVVM中进行验证

c# - 将 byte[] 转换为 Windows.UI.Xaml.Media.Imaging.BitmapImage

c# - 使用 Json.NET JsonSchemaGenerator 将 JSON Schema 属性(标题、描述)添加到 C# 类属性

c# - 在不使用不安全的情况下将 int 分配给结构对象

c# - 继承中的逆变

c# - Unity3D Slerp旋转速度

c# - Stanford CoreNLP 创建 edu.stanford.nlp.time.TimeExpressionExtractorImpl 时出错

c# - 制作两个 SharedPreferences