4

いくつDataGridViewかの列といくつかの行のデータがあります。列の 1 つはDataGridViewCheckBoxColumn(行の他のデータに基づいて) であり、一部の行でチェックボックスを「非表示」にするオプションが必要です。読み取り専用にする方法は知っていますが、まったく表示されないようにするか、少なくとも他のチェックボックスとは異なる方法で表示 (グレー表示) することをお勧めします。これは可能ですか?

4

3 に答える 3

12

いくつかの回避策: 読み取り専用にして、色をグレーに戻します。1 つの特定のセルの場合:

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

または、より良いが、より「複雑な」解決策:
2 つの列があるとします: 最初に数字があり、2 番目にチェックボックスがあり、数字が 2 より大きい場合は表示されませんCellPainting。休息の絵。DataGridView のイベントCellPaintingを追加します (空の行に新しいデータを追加するときの例外を回避するために、オプションで 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
            }
        }
    }
}

動作するはずですが、条件を確認する最初の列で値を手動で変更する場合は、2 番目のセルを更新する必要があるため、次のような別のイベントを追加しますCellValueChanged

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 0)
    {
        dataGridView1.InvalidateCell(1, e.RowIndex);
    }
}
于 2011-10-05T16:06:52.453 に答える
0

http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcheckboxcell.aspx

DataGridViewCheckBoxCell.Visible = false;

編集:ああ、待って、それは読み取り専用です。ダープ。

その場合は、セルを空の DataGridViewTextBoxCell に置き換えてみてください。

于 2011-10-05T15:55:54.787 に答える
0

Windows フォーム DataGridView コントロールのセルの外観をカスタマイズするから取得すると、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;
         }
      }
   }
}

唯一の注意点は、セルの1 つのプロパティdataGridView1.Invalidate();を変更するときに呼び出す必要があることです。ReadOnlyDataGridViewCheckBox

于 2011-10-05T16:33:35.470 に答える