c# – 未在可编辑的组合框中输入键入的文本

在我的datagridview中,我在
winforms.But中有一个textboxcolumn和一个可编辑的组合框列,同时在组合框文本中键入新值并按下回车键,我没有得到键入的值作为相应的单元格值.有人可以帮助这个.

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.

希望这可以帮助.

点赞