1
Answer

Changing Color of Datagridview Rows with effect of Days Qty.

Zeb Muhammad

Zeb Muhammad

7y
182
1
I facing problem to change color of DGV Row w.e.o Quantity of Remaining days. I tried it but i got error. PLease, check my code.
  1. public void RowsColor()  
  2.         {  
  3.             for (int i = 0; i < dataGridView1.Rows.Count; i++)  
  4.             {  
  5.                 int val = Int32.Parse(dataGridView1.Rows[i].Cells[5].Value.ToString());  
  6.                 if (val < 14)  
  7.                 {  
  8.                     dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red;  
  9.                 }  
  10.                 else  
  11.                 {  
  12.                     dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Green;  
  13.                 }  
  14.             }  
  15.         }  
and I called this
  1. private void btn_Show_Click(object sender, EventArgs e)  
  2.         {  
  3.             con.Open();  
  4.             SqlCommand cmd = con.CreateCommand();  
  5.             cmd.CommandType = CommandType.Text;  
  6.             cmd.CommandText = "SELECT pro_ID,pur_Date,pur_Batch as BatchNo, pur_ItemName as ItemName,pur_ExpDate as ExpiryDate, DATEDIFF(DAY, GETDATE(), pur_ExpDate) AS RemainingDays FROM pur_tab WHERE pur_Date BETWEEN '"+dt_From.Value.ToString("yyyy-MM-dd")+"' AND '"+ dt_To.Value.ToString("yyyy-MM-dd") + "'";  
  7.             cmd.ExecuteNonQuery();  
  8.             dt = new DataTable();  
  9.             da = new SqlDataAdapter(cmd);  
  10.             da.Fill(dt);  
  11.             dataGridView1.DataSource = dt;  
  12.             RowsColor();  
  13.             con.Close();  
  14.         }  
I got error An "unhandled exception of type 'System.NullReferenceException' occurred in MMS1.exe
 
“Object reference not set to an instance of an object.”}”
 
Please , help me. 
Answers (1)