C#DataGridViewCheckBoxColumn Hide / Gray-Out [英] C# DataGridViewCheckBoxColumn Hide/Gray-Out

查看:101
本文介绍了C#DataGridViewCheckBoxColumn Hide / Gray-Out的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 DataGridView ,其中有几列和几行数据。其中一列是一个 DataGridViewCheckBoxColumn 和(根据行中的其他数据),我想选择隐藏一些行中的复选框。我知道如何使它只读,但我宁愿它不显示,或至少显示不同于(灰色)比其他复选框。这是可能的吗?

I have a DataGridView with several columns and several rows of data. One of the columns is a DataGridViewCheckBoxColumn and (based on the other data in the row) I would like the option to "hide" the checkbox in some rows. I know how to make it read only but I would prefer it not show up at all or at least display differently (grayed out) than the other checkboxes. Is this possible?

谢谢!

推荐答案

它只读,将颜色更改为灰色。
对于一个特定的单元格:

Some workaround: make it read-only and change back color to gray. For one specific cell:

dataGridView1.Rows[2].Cells[1].Style.BackColor =  Color.LightGray;
dataGridView1.Rows[2].Cells[1].ReadOnly = true;

或者,更好但更复杂的解决方案:

假设你有2列:第一个带数字,第二个带有复选框,当数字> 2时不应该可见。您可以处理 CellPainting 事件,仅绘制边框(例如背景)并打破画的休息。为DataGridView添加事件 CellPainting (可选地测试DBNull值以避免在空行中添加新数据时出现异常):

Or, better but more "complicated" solution:
suppose you have 2 columns: first with number, second with checkbox, that should not be visible when number > 2. You can handle CellPainting event, paint only borders (and eg. background) and break painting of rest. Add event CellPainting for DataGridView (optionally test for DBNull value to avoid exception when adding new data in empty row):

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    //check only for cells of second column, except header
    if ((e.ColumnIndex == 1) && (e.RowIndex > -1))
    {
        //make sure not a null value
        if (dataGridView1.Rows[e.RowIndex].Cells[0].Value != DBNull.Value)
        {
            //put condition when not to paint checkbox
            if (Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value) > 2)
            {
                e.Paint(e.ClipBounds, DataGridViewPaintParts.Border | DataGridViewPaintParts.Background);  //put what to draw
                e.Handled = true;   //skip rest of painting event
            }
        }
    }
}

它应该可以工作,但是如果您在第一列中手动更改值,则检查条件,则必须刷新第二个单元格,因此添加另一个事件,如 CellValueChanged

It should work, however if you change value manually in first column, where you check condition, you must refresh the second cell, so add another event like CellValueChanged:

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 0)
    {
        dataGridView1.InvalidateCell(1, e.RowIndex);
    }
}

这篇关于C#DataGridViewCheckBoxColumn Hide / Gray-Out的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆