我想从数据库中检索数据后,要为数据库中的颜色上色。如果单元格文本具有" X",则将细胞为绿色颜色着色。我试图编写代码,但它不起作用。
这是我到目前为止的代码:
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);
}
有什么想法我该如何工作?
谢谢
您应该设置要更改的单元格的样式。
如果在下面加载数据并进入滚动事件的位置,则可以根据需要和可见单元格时为您的单元格着色。如果您有很多行
,这是一个重要的性能问题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);
}
}
}
}
}
}
希望这能让您更接近您的需求。
托马斯