Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I get a CheckBox column in a DataGrid to respond to the first click?

When you first click into a CheckBox column, the checked state of the cell does not change. One way you can make the checked state change on the first click is to handle the grid's MouseUp event, and change the check value there.

[C#]

private int checkBoxColumn = 9; // CheckBox column

private void dataGrid1_MouseUp( object sender, MouseEventArgs e )
{
  DataGrid.HitTestInfo hti = dataGrid1.HitTest( e.X, e.Y );
  try
  {
    if ( hti.Type == DataGrid.HitTestType.Cell &&
        hti.Column == checkBoxColumn )
      dataGrid1[ hti.Row, hti.Column ] = ! (bool) dataGrid1[ hti.Row, hti.Column ];
  }
  catch( Exception ex )
  {
    MessageBox.Show( ex.Message );
  }
}

[Visual Basic]

Private Sub DataGrid1_MouseUp(ByVal sender As Object, _
    ByVal e As MouseEventArgs) Handles DataGrid1.MouseUp
  Dim hti As DataGrid.HitTestInfo = DataGrid1.HitTest(e.X, e.Y)
  Try
    If hti.Type = DataGrid.HitTestType.Cell AndAlso _
        hti.Column = CheckBoxColumn Then
      DataGrid1(hti.Row, hti.Column) = Not CBool(DataGrid1(hti.Row, hti.Column))
    End If
  Catch ex As Exception
    MessageBox.Show(ex.Message)
  End Try
End Sub

Contributed from George Shepherd's Windows Forms FAQ