Datagridview cell conatins“xyz”(字符串)然后改变字体颜色 [英] Datagridview cell conatins "xyz"(string) then change font color

查看:68
本文介绍了Datagridview cell conatins“xyz”(字符串)然后改变字体颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的,





C#问题!



我如果它与其他字符串相等,我想更改datagridview中的单元格颜色。



你能帮助我吗?



Thx!

Dear All,


C# question!

I would like to change a cell color in datagridview if it is equal with an other string.

Could you help me?

Thx!

推荐答案

使用 DataGridView.RowPrePaint事件 [ ^ ] - 在绘制整行之前调用它,并允许您设置适当的单元格样式属性,无论你需要什么。



拼写错误[/ edit]
Use the DataGridView.RowPrePaint event[^] - it's called just before the whole row is painted, and allows you to set the appropriate cell Style property to whatever you need.

[edit]typos[/edit]


如果它是一个窗口表单项目您可以使用以下内容:



在设计器中添加int以订阅Cell end edit事件:

If it is a windows form project you can use the following:

Add int the designer the next line to subscribe to the Cell end edit event:
this.dataGridView1.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellEndEdit);





在事件处理程序中,您验证字符串:





And in the event handler you verify with you string:

private static const string yourString = "XYZ";

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    DataGridView dataGridView = (DataGridView)sender;

    if (dataGridView.CurrentCell.Value.ToString() == yourString)
    {
        dataGridView.CurrentCell.Style.ForeColor = Color.Red;
    }

}





您可以通过全部验证重复项单元格:





You can verify for duplicates by going thru all the cells:

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    DataGridView dataGridView = (DataGridView)sender;

    // Iterate thru all the cell and verifying if the text is a duplicate.
    for (int i = 0; i < dataGridView.ColumnCount; i++)
    {
        for (int j = 0; j < dataGridView.RowCount; j++)
        {
            if (dataGridView.Rows[j].Cells[i].Value != null)
            {
                if (dataGridView.Rows[j].Cells[i].Value.ToString() == dataGridView.CurrentCell.Value.ToString() && dataGridView.Rows[j].Cells[i] != dataGridView.CurrentCell)
                {
                    dataGridView.CurrentCell.Style.ForeColor = Color.Red;

                    // Optional you can set the value of the cell where you find the text
                    dataGridView.Rows[j].Cells[i].Style.ForeColor = Color.Red;

                }
            }
        }
    }
}


这篇关于Datagridview cell conatins“xyz”(字符串)然后改变字体颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆