簡體   English   中英

DataTable和DataGridView對象的問題

[英]Problem with the DataTable and DataGridView objects

我有以下問題

在我的應用中,我進行了一些計算,然后將它們放入DataTable對象中(6列,最重要的是數據)。 要查看結果,我將它們放入DataGridView對象中,這是我的問題。 根據最后一列中包含的數據,我想用適當的顏色標記單元格。 而且我不知道是否應該在DataGridView對象上執行此操作,因為這是用戶界面? 我在哪里可以做到? DataTable對象沒有樣式屬性?

非常感謝...

您可以使用DataGridView的CellPainting事件來根據其內容格式化單元格。

例如

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
        {

            switch (dataGridView1.Columns[e.ColumnIndex].DataPropertyName)
            {
                case "Description":
                    {
                        break;
                    }
                case "NormalRoom":
                    {
                        break;
                    }
                case "Colour1":
                case "Colour2":
                    {
                        Color co = Color.White;
                        if (e.Value != null && e.Value != DBNull.Value)
                        {
                            co = string2Color((string)e.Value);
                        }
                        e.CellStyle.BackColor = Color.White;
                        e.CellStyle.ForeColor = Color.Black;

等。

我已經完成了類似的事情:

 public void setABCColor(DataGridView DGV)
    {
        for (int i = 0; i < DGV.Rows.Count; i++)
        {
            if ((string)DGV.Rows[i].Cells[6].Value == "A")
            {
                DGV.Rows[i].Cells[6].Style.BackColor = Color.Green;
            }
            else if ((string)DGV.Rows[i].Cells[6].Value == "B")
            {
                DGV.Rows[i].Cells[6].Style.BackColor = Color.Blue;
            }
            else
            {
                DGV.Rows[i].Cells[6].Style.BackColor = Color.Red;
            }
        }
    }

這可以接受嗎? 這不會改變MVC設計模式的假設嗎?

我建議將邏輯放在datagridview的Cell Formatting事件中。 如果您的數據根據​​網格中的某些計算而動態變化,這些也將反映變化,例如

void myDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
            if (e.Value.ToString() == "A" )
                e.CellStyle.BackColor = Color.Red;
}

暫無
暫無

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

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