取消选择 datagridview 单元格中的组合框值 vb.net

问题描述 投票:0回答:0

我有一个包含 2 列(Column1 和 Column2)的简单数据网格视图。 Column1 中的单元格有一个 TextBox,Column2 中的单元格有一个带有两种颜色选项(蓝色或红色)的 ComboBox

首先,我想在该行的组合框中选择颜色时更改 datagridview 行的颜色,我使用 CellValueChanged 和 CurrentCellDirtyChanged 事件做得很好。没问题。

但是现在,我想添加一个 YesNo Message.Box 来确认颜色变化。当我确认更改(点击“是”)时它工作正常但当我不确认它时失败(点击“否”)。

我尝试了以下代码:

Public Class Form1
    Dim lastOption As String = "Blue"
    Private Sub DataGridView1_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
        If e.RowIndex > -1 Then
            Dim oldOption = DataGridView1.Rows(e.RowIndex).Cells("Column2").Value
            If e.ColumnIndex = 1 Then
                Dim optionChoosen As String = DataGridView1.Rows(e.RowIndex).Cells("Column2").Value.ToString
                Dim result = MessageBox.Show(" Are you sure you want to set this option?", "Are you sure?", MessageBoxButtons.YesNo)
                If optionChoosen = "Red" Then
                    If result = DialogResult.Yes Then
                        DataGridView1.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.Red
                        DataGridView1.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.White
                        lastOption = optionChoosen
                    Else
                        DataGridView1.Rows(e.RowIndex).Cells("Column2").Value = lastOption
                    End If
                ElseIf optionChoosen = "Blue" Then
                    If result = DialogResult.Yes Then
                        DataGridView1.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.Blue
                        DataGridView1.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.White
                        lastOption = optionChoosen
                    Else
                        DataGridView1.Rows(e.RowIndex).Cells("Column2").Value = lastOption
                    End If
                End If
            End If
        End If
    End Sub

    Private Sub DataGridView1_CurrentCellDirtyStateChanged(sender As Object, e As EventArgs) Handles DataGridView1.CurrentCellDirtyStateChanged
        If (DataGridView1.IsCurrentCellDirty) Then
            ' This fires the cell value changed handler below
            DataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
        End If
    End Sub
End Class

当我在组合框中选择一种颜色并确认时,行颜色会正确更改。 但是当我不确认时,我不知道如何“记住”该组合框最后选择的组合框选项,以便在 CellValueChanged 事件处理程序的“其他”分支中使用它:

  • 如您所见,我将最后选择的组合框值保存在 CellValueChanged 方法之外的“lastOption”变量中。
  • 启动消息框并且我选择“否”时,它会转到“其他”分支以将“lastOption”值分配给当前组合框选择(我必须选择一个来触发消息框)

我知道这段代码没有用,因为我必须使用“n”个变量来记住“n”个组合框值(每行一个),但我只将它用于单行测试。

如果你尝试这段代码,你会发现即使是一行它也不起作用,因为消息框被触发了两次(似乎,不确定,一次是用于组合框选择,另一次是在 '其他分支)。

如果有人能帮我解决,我将不胜感激。感谢您的宝贵时间!

combobox selection messagebox cancellation datagridviewcombobox
© www.soinside.com 2019 - 2024. All rights reserved.