根据其价值改变细胞样式?

时间:2013-02-08 11:30:20

标签: c# winforms datagridview

我正在创建一个基于表单和DataGridView控件的应用程序。

我正在绑定来自数据库的信息,我现在要做的是根据其值"Urgent","Haute","Normale"来更改列属性的字体样式和颜色。

这是我正在使用的代码,但它没有用,可能有人告诉我下面的代码出了什么问题?

代码:

private void ColorizeCellsbyValue() {

        DataGridViewCellStyle BoldRed = null;
        BoldRed = new DataGridViewCellStyle();
        BoldRed.Font = new Font("Tahoma", 9, FontStyle.Bold);
        BoldRed.ForeColor = Color.Red;

        DataGridViewCellStyle Red = null;
        Red = new DataGridViewCellStyle();
        Red.ForeColor = Color.Red;

        DataGridViewCellStyle Black = null;
        Black = new DataGridViewCellStyle();
        Black.ForeColor = Color.Black;
        string priority;
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            priority = row.Cells[3].Value.ToString();
            switch (priority)
            {
                //Change font 
                case "Urgent":
                    row.Cells[3].Style = BoldRed;
                    break;
                case "Haute":
                    row.Cells[3].Style = Red;
                    break;
                case "Normale":
                    row.Cells[3].Style = Black;
                    break;
                default:
                    row.Cells[3].Style = Black;
                    break;
            }
        }
}

2 个答案:

答案 0 :(得分:1)

尝试使用

row.Cells[3].Style.BackColor = <Color>;

用于ForeColor使用

row.Cells[3].Style.ForeColor = <Color>;

这应该有效。快乐的编码!

答案 1 :(得分:1)

您无需创建DataGridViewCellStyle来设计Column属性。试着找出我的简单例子

        foreach (DataGridViewRow rows in dataGridView1.Rows)
        {
            if (rows.Cells[3].RowIndex % 2 == 0)
            {
                rows.Cells[3].Style.Font = new Font("Tahoma", 9, FontStyle.Bold);
                rows.Cells[3].Style.BackColor = Color.Red;
            }
            else
            {
                rows.Cells[3].Style.Font = new Font("Arial", 9, FontStyle.Regular);
                rows.Cells[3].Style.BackColor = Color.Blue;
            }
        }

我对你的主要问题的回答是尝试使用.EditedFormattedValue.ToString()

        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            priority = row.Cells[3].EditedFormattedValue.ToString();
            switch (priority)
            {
                //Change font 
                case "Urgent":
                    row.Cells[3].Style = BoldRed;
                    break;
                case "Haute":
                    row.Cells[3].Style = Red;
                    break;
                case "Normale":
                    row.Cells[3].Style = Black;
                    break;
                default:
                    row.Cells[3].Style = Black;
                    break;
            }
        }