4

この質問への回答を高低で検索しました。この投稿の回答: DataGridView セルのボタンの色を変更すると、フォントに関する質問に回答されません。

私は次のことを試しました:

DataGridViewRow r = dataGridView.Rows[0];
r.Cells[1].Style.BackColor = Color.Red;

私も試しました:

DataGridViewButtonColumn btnCOl = new DataGridViewButtonColumn();
btnCOl.FlatStyle = FlatStyle.Popup;
DataGridViewRow r = dataGridView.Rows[0];
r.Cells[1].Style = new DataGridViewCellStyle { BackColor = Color.LightBlue };

それでも役に立たない。

次の行もコメントアウトしました。

// Application.EnableVisualStyles();

DataGridViewButtonColumn の単一のボタンの背景色を変更する方法を知っている人がいる場合は、助けてください。

編集: 列のセルに異なる色を設定したい.たとえば、一部は赤になり、他は緑になる. 列全体の色を設定したくありません。

4

2 に答える 2

6

列全体の BackColor を変更する

オプションとして、のFlatStyleプロパティをDataGridViewButtonColumn設定FlatStyle.BackColorて、必要な色に設定できます。

var C1 = new DataGridViewButtonColumn() { Name = "C1" };
C1.FlatStyle = FlatStyle.Flat;
C1.DefaultCellStyle.BackColor = Color.Red;

単一セルの BackColor を変更する

異なるセルに異なる色を設定したい場合はFlatStyle、列またはセルをに設定した後、異なるセルを異なる色Flatに設定するだけで十分Style.BackColorです:

var cell = ((DataGridViewButtonCell)dataGridView1.Rows[1].Cells[0]);
cell.FlatStyle =  FlatStyle.Flat;
dataGridView1.Rows[1].Cells[0].Style.BackColor = Color.Green;

条件付きでセルの色を元に戻したい場合は、CellFormattingセルの値に基づいてイベントで行うことができます。

ノート

Buttonフラット スタイルではなく、標準的なルック アンド フィールを好む場合は、CellPaintイベントを処理できます。

void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if (e.RowIndex < 0 || e.ColumnIndex < 0)
        return;
    if (e.ColumnIndex == 0) // Also you can check for specific row by e.RowIndex
    {
        e.Paint(e.CellBounds, DataGridViewPaintParts.All
            & ~( DataGridViewPaintParts.ContentForeground));
        var r = e.CellBounds;
        r.Inflate(-4, -4);
        e.Graphics.FillRectangle(Brushes.Red, r);
        e.Paint(e.CellBounds, DataGridViewPaintParts.ContentForeground);
        e.Handled = true;
    }
}
于 2016-10-27T07:26:40.137 に答える
4

これを試して

DataGridViewButtonCell bc = new DataGridViewButtonCell();
bc.FlatStyle = FlatStyle.Flat;
bc.Style.BackColor = Color.AliceBlue;

このセルを必要な行に割り当てることができます

これは、フォームに既に挿入されているDataGridView dgvSampleを使用した小さな例です。

for (int i = 0; i <= 10; i++)
{
    DataGridViewRow fr = new DataGridViewRow();
    fr.CreateCells(dgvSample);

    DataGridViewButtonCell bc = new DataGridViewButtonCell();
    bc.FlatStyle = FlatStyle.Flat;

    if (i % 2 == 0)
    {
        bc.Style.BackColor = Color.Red;
    }   
    else
    {
        bc.Style.BackColor = Color.Green;
    }

    fr.Cells[0] = bc;
    dgvSample.Rows.Add(fr);
}
于 2016-10-27T07:38:43.883 に答える