2015-06-27 80 views
0

如果在數據庫中找到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(); 
    } 
} 
+1

'dataGridView1.Rows [I] .Cells [0] = .DefaultCellStyle.BackColor Color.red;' – Fabio

+0

沒有 .defaulcellstyle.backcolor =細胞之後color.red [0] – Daryl

+0

對於[各個細胞](http://stackoverflow.com/a/17728171/3773066)。 – OhBeWise

回答

0

得到的回答我自己的問題。

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

它工作得很好!

+0

這將改變整個'Row'的'BackColor'。如果你只是想爲單個'Cell'設置'BackColor',請參閱下面的答案。 –

+1

實際上,我刪除了我的答案,因爲您不想在「CellFormatting」事件處理程序中訪問數據庫。上面的@OhBeWise鏈接的答案正是你想要格式化單個'Cell'的內容。 –