如何根据“是”/“否”列更改VB.NET中的CheckBox.Checked

时间:2015-08-03 01:33:28

标签: vb.net checkbox datagridview string-comparison

我的表单中包含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

UPATE:

我将我的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

1 个答案:

答案 0 :(得分:0)

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

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