【问题标题】:Need to know the status of a checkbox cell in a DataGridView需要知道 DataGridView 中复选框单元格的状态
【发布时间】:2012-06-04 10:34:30
【问题描述】:

我有一个使用三列 DataGridView 的 C# Windows 应用程序。第一个是不需要验证的文本框。第二列和第三列都是复选框。我需要帮助确定这些框是否被选中。如果是,那么我想将复选框单元格的背景颜色设置为红色。我为此使用 DataGridView1_CellContentClick 事件。任何帮助或建议将不胜感激。

【问题讨论】:

  • 我忘了说。数据由用户输入,而不是来自 DataSource。

标签: datagridview checkbox


【解决方案1】:

试试这个

void DataGridView1_CellValueChanged(object sender System.Windows.Forms.DataGridViewCellEventArgs e)
{
  if( (bool)DataGridView1.Rows[e.RowIndex].Cells[ e.ColumnIndex].Value )
             DataGridView1.Rows[e.RowIndex].Cells[ e.ColumnIndex].DefaultCellStyle.BackColor  = Color.Red;
}

【讨论】:

  • 我需要代码来确定该框是选中还是未选中。
  • 如果单击的单元格是 DataGridViewCheckBoxCell DataGridView1.Rows[e.RowIndex].Cells[ e.ColumnIndex].Value 如果选中则返回 true,未选中则返回 false
  • “DefaultCellStyle.BackColor”出现构建错误。它指出“'System.Windows.Forms.DataGridViewCell'不包含'DefaultCellStyle'的定义......”我将其更改为“DataGridView.BackgroundColor”。我的代码现在可以编译,但在“DataGridView.BackgroundColor”上出现错误。它指出“索引超出范围。必须为非负数且小于集合的大小。参数名称:索引”。当应用程序在我尝试输入新行之前和表单显示之前运行时触发此事件。
  • 我忘了提到即使您通过代码向 gridview 添加行时也会触发此事件。因此,如果是这种情况,只需将行添加到 gridview,然后将事件附加到 gridview
【解决方案2】:

尝试以下方法:

    bool test=false;
         test=Convert.Toboolean(DataGridView1.Rows[0].cells[0].Value);
   // if test=true then
   // its checked and if no then its unchecked. 

【讨论】:

    【解决方案3】:
    Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
        Try
            If e.ColumnIndex = 8 Then
                Label1.Text = DataGridView1.Rows(e.RowIndex).Cells(0).Value
                FrmVisits.Show()
    
            ElseIf e.ColumnIndex = 9 Then
                Label1.Text = DataGridView1.Rows(e.RowIndex).Cells(0).Value
                FrmPEdit.Show()
            Else
                Exit Sub
            End If
        Catch ex As Exception
            Exit Sub
        End Try
    
    
    
    
    End Sub
    

    【讨论】:

      猜你喜欢
      • 2015-06-06
      • 2015-04-28
      • 2012-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-22
      • 1970-01-01
      • 2012-10-27
      相关资源
      最近更新 更多