2011-10-05 77 views
4

我有一个DataGridView与几列和几行数据。其中一列是DataGridViewCheckBoxColumn和(基于行中的其他数据)我希望在某些行中“隐藏”复选框。我知道如何让它只读,但我宁愿它根本不显示,或至少显示不同(灰色)比其他复选框。这可能吗?C#DataGridViewCheckBoxColumn Hide/Gray-Out

回答

12

某些解决方法:将其设置为只读并将颜色更改为灰色。 对于一个特定的细胞:

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

或者更好,但更“复杂”的解决方案:
假设你有2列:先用数量,第二,复选框,应该是不可见的,当数> 2。您可以处理CellPainting事件,仅绘制边框(例如背景)并打破休息的绘制。添加事件CellPainting为DataGridView中(可选测试的DBNull值,以避免异常增加的空行新数据时):

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

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

Customize the Appearance of Cells in the Windows Forms DataGridView Control两者,你可以赶上CellPainting事件,如果以只读模式不绘制细胞。例如:

public Form1() 
{ 
    InitializeComponent(); 
    dataGridView1.CellPainting += new 
     DataGridViewCellPaintingEventHandler(dataGridView1_CellPainting); 
} 

private void dataGridView1_CellPainting(object sender, 
    System.Windows.Forms.DataGridViewCellPaintingEventArgs e) 
{ 
    // Change 2 to be your checkbox column # 
    if (this.dataGridView1.Columns[2].Index == e.ColumnIndex && e.RowIndex >= 0) 
    { 
     // If its read only, dont draw it 
     if (dataGridView1[e.ColumnIndex, e.RowIndex].ReadOnly) 
     { 
     // You can change e.CellStyle.BackColor to Color.Gray for example 
     using (Brush backColorBrush = new SolidBrush(e.CellStyle.BackColor)) 
     { 
      // Erase the cell. 
      e.Graphics.FillRectangle(backColorBrush, e.CellBounds); 
      e.Handled = true; 
     } 
     } 
    } 
} 

唯一需要注意的是,你需要调用dataGridView1.Invalidate();当你改变DataGridViewCheckBox细胞的之一ReadOnly财产。

相关问题