0

Dear Friends,
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.

public void RowsColor()
        {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                int val = Int32.Parse(dataGridView1.Rows[i].Cells[5].Value.ToString());
                if (val < 14)
                {
                    dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                }
                else
                {
                    dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Green;
                }

            }
        }

and

private void btn_Show_Click(object sender, EventArgs e)
        {
            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            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") + "'";
            cmd.ExecuteNonQuery();
            dt = new DataTable();
            da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            dataGridView1.DataSource = dt;
            RowsColor();
            con.Close();
        }

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.

2
Contributors
4
Replies
18
Views
4 Weeks
Discussion Span
Last Post by ddanbe
0
public void RowsColor()
        {
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {

 int val =Int32.Parse(dataGridView1.Rows[i].Cells[5].Value.ToString());

                if (val < 14)

                {
                    dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                }
                else
                {
                    dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Green;
                }
            }
        }

Please, check

int val =Int32.Parse(dataGridView1.Rows[i].Cells[5].Value.ToString());
1

You don't have to use ToString if Value comes from a cell of a TextBoxColumn.
You did not answer my question: on wich line did the error occur? Please do.

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.