【问题标题】:Conditionally Change Cell Color有条件地更改单元格颜色
【发布时间】:2015-09-14 02:27:48
【问题描述】:

如果在数据库中找到InvoiceNo,我想更改DataGridView 中指定单元格的单元格颜色。

以下是我的查询:

for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    invoiceno = dataGridView1.Rows[i].Cells[0].Value.ToString();
    accpacInv = dataGridView1.Rows[i].Cells[1].Value.ToString();
    Customer = dataGridView1.Rows[i].Cells[2].Value.ToString();
    Invdate = dataGridView1.Rows[i].Cells[3].Value.ToString();
    Duedate = dataGridView1.Rows[i].Cells[4].Value.ToString();
    cur = dataGridView1.Rows[i].Cells[5].Value.ToString();
    LocAm = dataGridView1.Rows[i].Cells[6].Value.ToString();

    SqlConnection con = new SqlConnection(DbClass.StrdBase);
    con.Open();
    SqlCommand cmd = new SqlCommand("Select InvoiceNo from tblarmon     where invoiceno = '" + invoiceno  +  "'", con);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);

    if (dt.Rows.Count > 0)
    {
        // Change the Cell color of the selected cell.(if record already found ind databae)
    }
    else
    {
        con.Close();
        SaveRecordtoDB();
    }
}

【问题讨论】:

  • dataGridView1.Rows[i].Cells[0].DefaultCellStyle.BackColor = Color.red;
  • 单元格[0]后没有.defaulcellstyle.backcolor= color.red
  • 对于individual cells
  • 此外,实现IDisposable 的类的实例,如SqlConnectionSqlCommandSqlDataAdapter 应按照this example 包装在using 语句中。

标签: c# datagridview colors cell


【解决方案1】:

得到了我自己问题的答案。

dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.LightPink;

效果很好!

【讨论】:

  • 这将改变整个RowBackColor。如果您只想为个人Cell 设置BackColor,请参阅下面的答案。
  • 实际上,我删除了我的答案,因为您不想在 CellFormatting 事件处理程序中访问数据库。如果您想格式化个人Cell,上面@OhBeWise 链接的答案正是您正在寻找的。​​span>
猜你喜欢
  • 2014-05-03
  • 2016-07-01
  • 2013-10-23
  • 2017-03-10
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 2013-03-23
相关资源
最近更新 更多