簡體   English   中英

使用數據源時無法更改datagridview單元格顏色

[英]Can't change datagridview cell color when using a datasource

我有一個有趣的問題。 我試圖使用數據表作為datagridview的數據源。 我想為表中的一些單元格着色以指示各種事物,但由於某種原因,顏色將不會顯示。 因此,以下代碼顯示了一個未着色的單元格。

dataGridView1.DataSource = table;

dataGridView1.Rows[0].Cells[0].Style.BackColor = Color.Yellow;

我只能在初始表單加載后顯示顏色(例如在OnClick事件上設置單元格顏色)。 但是,如果我在下面的代碼中顯式創建視圖的行和列,則着色有效。

foreach (DataColumn col in table.Columns)
    dataGridView1.Columns.Add(col.ColumnName, col.ColumnName);

for (int i = 0; i < table.Rows.Count; i++)
{
    var row = table.Rows[i];
    object[] values = new object[table.Columns.Count];
    for (int x = 0; x < table.Columns.Count; x++)
        values[x] = row[x].ToString();

    dataGridView1.Rows.Add(values);
}

dataGridView1.Rows[0].Cells[0].Style.BackColor = Color.Yellow;

我不想以這種方式獲得代碼。 有誰知道這里發生了什么阻止我着色細胞?

如果你嘗試在數據綁定完成之前在表單的構造函數中設置單元格顏色,那么單元格的更改就不會粘連(不要問我原因,只是其中一個與DataGridView

對此最直接的解決方法是稍后設置顏色 - 通常在DataBindingComplete事件處理程序中:

void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    dataGridView1.Rows[0].Cells[0].Style.BackColor = Color.Yellow;
}

這適用於網格的靜態着色 - 如果您希望顏色根據網格內的更改而更改,則使用CellFormatting事件更改單元格。

這是我最近實施的,我不知道它是否會有所幫助?

private void dgvOutstandingReports_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
            {
                int colIndex = e.ColumnIndex;
                int rowIndex = e.RowIndex;


                if (rowIndex >= 0 && colIndex >= 0)
                {
                    DataGridViewRow theRow = dgvOutstandingReports.Rows[rowIndex];


                    if (theRow.Cells[colIndex].Value.ToString() == "Daily Report")
                    {
                        theRow.DefaultCellStyle.BackColor = Color.LightYellow;
                    }
                    else if (theRow.Cells[colIndex].Value.ToString() == "Monthly Report")
                    {
                        theRow.DefaultCellStyle.BackColor = Color.LightGray;
                    }
                    else if (theRow.Cells[colIndex].Value.ToString() == "SMP Report")
                    {
                        theRow.DefaultCellStyle.BackColor = Color.Snow;
                    }
                    else if (theRow.Cells[colIndex].Value.ToString() == "Weekly Report")
                    {
                        theRow.DefaultCellStyle.BackColor = Color.Pink;
                    }
                    else if (theRow.Cells[colIndex].Value.ToString() == "Hourly Report")
                    {
                        theRow.DefaultCellStyle.BackColor = Color.LightSteelBlue;
                    }
                }
            }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM