代码之家  ›  专栏  ›  技术社区  ›  bitbonk

更改选择时直接应用和验证绑定的DataGridViewComboBoxCell

  •  3
  • bitbonk  · 技术社区  · 15 年前

    我有Windows窗体 DataGridView 里面有一些 DataGridViewComboBoxCell 绑定到源集合的 DataSource , DisplayMember ValueMember 属性。当前,组合框单元格提交更改(即 DataGridView.CellValueChanged 只有在我单击另一个单元格后,组合框单元格才会失去焦点。

    在组合框中选择新值后,我如何理想地直接提交更改。

    3 回复  |  直到 13 年前
        1
  •  1
  •   Bradley Smith    15 年前

    这种行为被写入 DataGridViewComboBoxEditingControl . 谢天谢地,它可以被改写。首先,必须创建上述编辑控件的子类,覆盖 OnSelectedIndexChanged 方法:

    protected override void OnSelectedIndexChanged(EventArgs e) {
        base.OnSelectedIndexChanged(e);
    
        EditingControlValueChanged = true;
        EditingControlDataGridView.NotifyCurrentCellDirty(true);
        EditingControlDataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
    }
    

    这将确保 DataGridView 当组合框中的项目选择发生更改时会得到正确通知。

    然后你需要子类 DataGridViewComboBoxCell 并覆盖 EditType 属性从上面返回编辑控件子类(例如 return typeof(MyEditingControl); )这将确保在单元格进入编辑模式时创建正确的编辑控件。

    最后,您可以设置 CellTemplate 您的财产 DataGridViewComboBoxColumn 到cell子类的实例(例如 myDataGridViewColumn.CellTemplate = new MyCell(); )这将确保为网格中的每一行使用正确类型的单元格。

        2
  •  0
  •   Community Mohan Dere    8 年前

    我试过用 Bradley's suggestion ,但它对附加单元格模板时很敏感。似乎我不能让设计视图连接到这个列,我必须自己做。

        private void bindingSource_PositionChanged(object sender, EventArgs e)
        {
            (MyBoundType)bindingSource.Current.MyBoundProperty = 
                ((MyChoiceType)comboBindingSource.Current).MyChoiceProperty;
        }
    
        3
  •  0
  •   Danny    13 年前

    Private _currentCombo As ComboBox
    
    Private Sub grdMain_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles grdMain.EditingControlShowing
        If TypeOf e.Control Is ComboBox Then
            _currentCombo = CType(e.Control, ComboBox)
            AddHandler _currentCombo.SelectedIndexChanged, AddressOf SelectionChangedHandler
        End If
    End Sub
    
    Private Sub grdMain_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grdMain.CellEndEdit
        If Not _currentCombo Is Nothing Then
            RemoveHandler _currentCombo.SelectedIndexChanged, AddressOf SelectionChangedHandler
            _currentCombo = Nothing
        End If
    End Sub
    
    Private Sub SelectionChangedHandler(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim myCombo As ComboBox = CType(sender, ComboBox)
        Dim newInd As Integer = myCombo.SelectedIndex
    
        //do whatever you want with the new value
    
        grdMain.NotifyCurrentCellDirty(True)
        grdMain.CommitEdit(DataGridViewDataErrorContexts.Commit)
    End Sub
    

    推荐文章