开发者

Problem with the DataTable and DataGridView objects

I have the following problem

In my aplication I doing some calculations and after it put them into DataTable object (6 columns, data in the latest one is most importan开发者_运维百科t). To view the results I put them into DataGridView object and there is my problem. Depending on the data contained in the last column I want to mark the cells on the appropriate colors. And I don't know if I should do this on the DataGridView object because this is user interfaces? Where I can do this? DataTable object doesn't have a style properties?

Thanks a lot...


You can use the CellPainting event of the DataGridView to format your cells based on their content.

e.g. `

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;

etc.`


I've done simething like this:

 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;
            }
        }
    }

Is this acceptable? Is this not change the assumption of the MVC design pattern?


I would recommend putting the logic in the Cell Formatting event of the datagridview. These would also reflect changes in case your data changes dynamically based on some calculations in the grid something like

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜