36

データが取り込まれた dataGridView オブジェクトがあります。ボタンをクリックして、セルの背景色を変更したい。これは私が現在持っているものです

foreach(DataGridViewRow row in dataGridView1.Rows)
{
    foreach(DataGridViewColumn col in dataGridView1.Columns)
    {
            //row.Cells[col.Index].Style.BackColor = Color.Green; //doesn't work
            //col.Cells[row.Index].Style.BackColor = Color.Green; //doesn't work
        dataGridView1[col.Index, row.Index].Style.BackColor = Color.Green; //doesn't work
    }
} 

これら 3 つのすべてにより、テーブルがオーバーラップして再描画され、テーブルのサイズを変更しようとすると混乱します。セルをクリックすると、値が強調表示されたままになり、背景色は変わりません。

Q: テーブルが作成された後で個々のセルの背景色を変更するにはどうすればよいですか?

4

5 に答える 5

85

これは私のために働く

dataGridView1.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.Red;
于 2013-07-18T15:46:10.573 に答える
4

DataGridViewTextBoxCell の独自の拡張機能を実装し、次のように Paint メソッドをオーバーライドします。

class MyDataGridViewTextBoxCell : DataGridViewTextBoxCell
{
    protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex,
        DataGridViewElementStates cellState, object value, object formattedValue, string errorText,
        DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
    {
        if (value != null)
        {
            if ((bool) value)
            {
                cellStyle.BackColor = Color.LightGreen;
            }
            else
            {
                cellStyle.BackColor = Color.OrangeRed;
            }
        }
        base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value,
            formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
}

}

次に、コードで、列の CellTemplate プロパティをクラスのインスタンスに設定します

columns.Add(new DataGridViewTextBoxColumn() {CellTemplate = new MyDataGridViewTextBoxCell()});
于 2016-02-22T12:05:28.960 に答える
1

ありがとうございます

ここで、qtyフィールドがゼロであることは、セルが赤色であることを示していることを意味します

        int count = 0;

        foreach (DataGridViewRow row in ItemDg.Rows)
        {
            int qtyEntered = Convert.ToInt16(row.Cells[1].Value);
            if (qtyEntered <= 0)
            {
                ItemDg[0, count].Style.BackColor = Color.Red;//to color the row
                ItemDg[1, count].Style.BackColor = Color.Red;

                ItemDg[0, count].ReadOnly = true;//qty should not be enter for 0 inventory                       
            }
            ItemDg[0, count].Value = "0";//assign a default value to quantity enter
            count++;
        }

    }
于 2014-06-17T07:43:06.540 に答える