如何根据列值更改行颜色

时间:2013-04-30 05:37:32

标签: c# datagridview nullreferenceexception

我使用此代码但是没有将错误对象引用设置为对象的实例。

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 个答案:

答案 0 :(得分:1)

检查此行。

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

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

给出空值。

如果可能的话,通过将当前行的索引作为:

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

希望它有所帮助。