2013-04-30 120 views
0

我使用此代碼但給出的錯誤對象引用未設置爲對象的實例。如何根據列值更改行顏色

using (SqlConnection sqlConn = new SqlConnection("Data Source=OMKAR-PC;Initial Catalog=omkar;Persist Security Info=True;User ID=sa;Password=omkar;Pooling=False")) 
    { 
     sqlConn.Open(); 

     using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM customer ", sqlConn)) 
     { 
      DataTable t = new DataTable(); 
      a.Fill(t); 
      dataGridView1.DataSource = t; 

      this.dataGridView1.CellFormatting += 
new DataGridViewCellFormattingEventHandler(dataGridView1_CellFormatting); 


     foreach (DataGridViewRow row in dataGridView1.Rows) 
     { 
      try 
      { 
      string CNumColour = dataGridView1.CurrentRow.Cells[0].FormattedValue.ToString(); 
      if (CNumColour != null) 
      { 
       foreach (DataGridViewCell cells in row.Cells) 
       { 
       if (CNumColour == "yes") 
        { 
        cells.Style.ForeColor = Color.Pink; 
        } 
        else if (CNumColour == "no") 
        { 
        cells.Style.ForeColor = Color.Red; 
        } 
       } 
       } 
      } 
     catch (System.Exception ex) 
     { 

     } 
     } 
     sqlConn.Close(); 
    } 
+1

哪條線給出錯誤? – Aditi 2013-04-30 05:40:36

回答

1

檢查這條線。

string CNumColour = dataGridView1.CurrentRow.Cells[0].FormattedValue.ToString(); 

dataGridView1.CurrentRow.Cells[0].FormattedValue.ToString(); 

給出空值。

如果有可能通過給當前行的索引嘗試:

dataGridView1.Rows[row.RowIndex].Cells[0].FormattedValue.ToString(); 

希望它有幫助。