[英]How to change dataGridView cell color on text condition in C#
我想为dataGridView单元从数据库中检索数据后着色。 如果单元格文本具有“ X”,则使用GreenYellow颜色为单元格着色。 我试图编写代码,但是没有用。
这是我到目前为止的代码:
private void button2_Click(object sender, EventArgs e)
{
string constring = "Data Source = localhost; port = 3306; username = root; password = 0159";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand("Select * from TopShineDB.Table1 ;", conDataBase);
using (MySqlConnection conn = new MySqlConnection(constring))
{
try {
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdDataBase;
DataTable dt = new DataTable();
sda.Fill(dt);
foreach (DataRow item in dt.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = item["Timee"].ToString();
dataGridView1.Rows[n].Cells[1].Value = item["CarColorNumber"].ToString();
dataGridView1.Rows[n].Cells[2].Value = item["Interior"].ToString();
dataGridView1.Rows[n].Cells[3].Value = item["Exterior"].ToString();
if (dataGridView1.CurrentCell.Value == item["Interior"] + " X".ToString())
{
dataGridView1.CurrentCell.Style.BackColor = Color.GreenYellow;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
有什么想法可以使它起作用吗?
谢谢
您应该设置要更改的单元格的样式。
如果您在下面的方法中将数据加载到Scroll事件中,并且该方法包括在Scroll事件中,则该方法将根据需要为您的单元格着色,并且仅在该单元格可见时才进行着色。 如果您有很多行,这是一个重要的性能问题
public void SetRowColor()
{
try
{
for (int i = 0; i < this.dataGridView.Rows.Count; i++)
{
if (this.dataGridView.Rows[i].Displayed)
{
if (this.dataGridView.Columns.Contains("Interior"))
{
if ((int)this.dataGridView.Rows[i].Cells["Interior"].Value == "X")
{
this.dataGridView.Rows[i].Cells["Interior"].Style.BackColor = Color.Green;
this.dataGridView.Rows[i].Cells["Interior"].Style.ForeColor = Color.White;
this.dataGridView.InvalidateRow(i);
}
else
{
this.dataGridView.Rows[i].Cells["Interior"].Style.BackColor = Color.White;
this.dataGridView.Rows[i].Cells["Interior"].Style.ForeColor = Color.Black;
this.dataGridView.InvalidateRow(i);
}
}
}
}
}
}
希望这能使您更接近所需。
汤玛士
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.