【问题标题】:How to change CheckBox.Checked in VB.NET based on "yes"/"no" column如何根据“是”/“否”列在 VB.NET 中更改 CheckBox.Checked
【发布时间】:2022-03-22 12:08:45
【问题描述】:

我有一个带有DataGridViewCheckBox 的表单。我想要的是当DataGridView 索引更改时它应该更改CheckBox 选中状态,或者如果我按下箭头向下或向上CheckBox 应该根据单元格值更改。这是我的代码:

Public Sub cellclick()
    Dim row As DataGridViewRow
    Dim r As Integer = usergrid.CurrentRow.Index
    row = Me.usergrid.Rows(r)
   'the value of the cell("ACCES1") maybe yes or no
    If row.Cells("ACCESS1").Value.ToString = "YES" Then
        CheckBox1.CheckState = CheckState.Checked
        'i also try checkbox1.checked=true
    ElseIf row.Cells("ACCESS1").Value.ToString = "NO" Then
        CheckBox1.CheckState = CheckState.Unchecked
        'i also try checkbox1.checked=false
    End If
End Sub 

Private Sub usergrid_CellEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles usergrid.CellEnter
    cellclick()
End Sub

更新:

我将 if else 代码更改为以下代码行,但仍然无法正常工作,这是我的新代码:

    If row.Cells("ACCESS1").Value = "YES" Then
        CheckBox1.Checked = True
        MsgBox(row.Cells("ACCESS1").Value) 'this is working and it echoes me the cell content everytime i click or change the grid index. it message me to "YES" and sometimes "NO" depends upon on the cell content/value
    Else
        CheckBox1.Checked = False
        MsgBox(row.Cells("ACCESS1").Value) 'this is working and it echoes me the cell content everytime i click or change the grid index
    End If

【问题讨论】:

  • access1 的可能值为'yes' or 'no'
  • 调试你的代码。将断点放在cellclick 函数中。好像没有调用你的函数,CellEnter 事件没有触发
  • CellEnter 与当前行更改索引之间存在差异。哪一个?还有你在说什么上下箭头?
  • 您可以查看:RowEnter 或 RowLeave 事件,因为这会触发索引更改...从那里执行您需要的操作。
  • @436f6465786572 cellenter 可能,但它在cellcontentclick and cellenter event 中仅适用于 msgbox 行(问题已更新)。我的意思是它在键盘上按上下箭头..

标签: vb.net checkbox datagridview string-comparison


【解决方案1】:

我认为您没有获得当前行。因为您的功能不专注于它。所以在方法和调用中进行以下更改:

Private Sub usergrid_CellEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles usergrid.CellEnter
    cellclick(e)
End Sub
Public Sub cellclick(ByVal e As System.Windows.Forms.DataGridViewCellEventArgs)
    Dim row As DataGridViewRow
    row = Me.usergrid.Rows(e.RowIndex)
    If row.Cells("ACCESS1").Value.ToString = "YES" Then
        CheckBox1.CheckState = CheckState.Checked         
    ElseIf row.Cells("ACCESS1").Value.ToString = "NO" Then
        CheckBox1.CheckState = CheckState.Unchecked          
    End If
 End Sub 

【讨论】:

  • 你的建议仍然不起作用..我不知道我的代码和你的代码有什么问题..但它真的不起作用
  • 放断点并检查row.Cells("ACCESS1").Value.ToString的值
  • 我做到了。 row.Cells("ACCESS1").Value.ToString 给了我来自datagridview 的正确值,唯一的问题是checkbox1 在调用cellclick(e) 时它不会改变.. 它实际上让我进入msgbox 单元格的值
猜你喜欢
  • 2019-08-22
  • 1970-01-01
  • 1970-01-01
  • 2021-12-11
  • 1970-01-01
  • 2019-02-18
  • 1970-01-01
  • 2015-05-27
  • 2010-09-15
相关资源
最近更新 更多