简体   繁体   English

如何根据列值更改行颜色

[英]how to change row color based on column value

i using this code but giving error object reference is not set to instance of object. 我使用此代码,但给出错误的对象引用未设置为对象实例。

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();
     }

Check for this line. 检查这一行。

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

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

is giving null value. 给空值。

If possible try it by giving index of current row as: 如果可能,尝试通过将当前行的索引设置为:

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

Hope its helpful. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM