2011-10-05 33 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財產。

相關問題