DataGridView.IsCurrentRowDirty()未使用可编辑的DataGridViewComboBoxColumn设置

时间:2013-04-12 20:00:29

标签: c# winforms datagridview

我有一个DataGridViewDataGridViewComboBoxColumnList<IBrand>绑定。在此组合框列中,我允许用户选择现有值或键入新值。当用户选择现有值时,IsCurrentRowDirty()会正确返回true。当用户键入值时,IsCurrentRowDirty()总是返回false,显然应该返回true。

我已尝试在DataGridView.CommitEdit()事件中调用CurrentCellDirtyStateChanged,但这不起作用

如何在DataGridViewComboBoxColumn中输入用户输入的值以将行设置为脏?

相关代码如下。

谢谢,

凯尔

        public void BindBrands()
        {
            DataGridViewComboBoxColumn comboBox = (DataGridViewComboBoxColumn)dgvReference.Columns[(int)ReferenceColumnsIndex.Brand];

            comboBox.DisplayMember = "Name";
            comboBox.ValueMember = "Self"; //"Self" returns "this"
            comboBox.DataSource = brands;
        }


            //This enables the DataGridViewComboBoxColumn to be editable by the user
            private void dgvReference_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
            {
                DataGridViewComboBoxColumn column = GetColumn<DataGridViewComboBoxColumn>(dgvReference,

                (int) ReferenceColumnsIndex.Brand);

            if (column != null)
            {
                ComboBox comboBox = e.Control as ComboBox;
                if (comboBox != null)
                {
                    comboBox.DropDownStyle = ComboBoxStyle.DropDown;
                }
            }
        }

        private void dgvReference_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            switch (e.ColumnIndex)
            {
                case (int)ReferenceColumnsIndex.Brand:

                    DataGridViewComboBoxColumn comboBox = dgvReference.Columns[(int)ReferenceColumnsIndex.Brand] as DataGridViewComboBoxColumn;
                    if (e.ColumnIndex == comboBox.DisplayIndex)
                    {
                        IBrand brand = new Brand(e.FormattedValue.ToString());
                        if (!brands.Contains(brand))
                        {
                            //If the brand does not exist, add it to the datasource of the combobox
                            brands.Add(brand);
                            dgvReference.NotifyCurrentCellDirty(true); //<== THIS LINE FIXES THE ISSUE

                        }

                        //When setting the .Value to brand here, IsCurrentRowDirty() does not return true
                        dgvReference.Rows[e.RowIndex].Cells[(int)ReferenceColumnsIndex.Brand].Value = brand;
                    }

                    break;
    }
}

1 个答案:

答案 0 :(得分:2)

好的,我想出了如何强制IsCurrentRowDirty()方法返回true。我需要添加以下代码行,如我的示例所示:

dgvReference.NotifyCurrentCellDirty(true);

在新输入的品牌上调用此选项将强制该行在IsCurrentRowDirty()方法中返回true。