首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

DataGridView中的CheckBox值始终为真

是因为在默认情况下,DataGridView中的CheckBox列是只读的,无法通过用户交互来改变其值。如果需要实现可编辑的CheckBox列,可以通过以下步骤来实现:

  1. 在DataGridView中添加一个CheckBox列,并设置其ReadOnly属性为False,使其可编辑。
  2. 在DataGridView的CellFormatting事件中,将CheckBox列的值设置为对应数据源中的值。这样可以确保CheckBox列的值与数据源中的值保持一致。
  3. 在DataGridView的CellContentClick事件中,监听CheckBox列的点击事件。当用户点击CheckBox时,可以通过修改数据源中对应行的值来改变CheckBox的值。

以下是一个示例代码:

代码语言:txt
复制
// 添加CheckBox列
DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
checkBoxColumn.HeaderText = "选择";
checkBoxColumn.Name = "checkBoxColumn";
checkBoxColumn.ReadOnly = false;
dataGridView1.Columns.Add(checkBoxColumn);

// 设置CellFormatting事件
dataGridView1.CellFormatting += DataGridView1_CellFormatting;

// 设置CellContentClick事件
dataGridView1.CellContentClick += DataGridView1_CellContentClick;

// CellFormatting事件处理方法
private void DataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex == dataGridView1.Columns["checkBoxColumn"].Index && e.RowIndex >= 0)
    {
        DataGridViewCheckBoxCell cell = dataGridView1.Rows[e.RowIndex].Cells["checkBoxColumn"] as DataGridViewCheckBoxCell;
        if (cell != null)
        {
            // 设置CheckBox列的值为对应数据源中的值
            cell.Value = dataGridView1.Rows[e.RowIndex].Cells["YourDataPropertyName"].Value;
        }
    }
}

// CellContentClick事件处理方法
private void DataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == dataGridView1.Columns["checkBoxColumn"].Index && e.RowIndex >= 0)
    {
        DataGridViewCheckBoxCell cell = dataGridView1.Rows[e.RowIndex].Cells["checkBoxColumn"] as DataGridViewCheckBoxCell;
        if (cell != null)
        {
            // 修改数据源中对应行的值来改变CheckBox的值
            bool currentValue = (bool)cell.Value;
            dataGridView1.Rows[e.RowIndex].Cells["YourDataPropertyName"].Value = !currentValue;
        }
    }
}

这样,当用户点击CheckBox时,CheckBox的值会根据数据源中的值进行切换。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的结果

领券