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.

Recommended Answers

All 4 Replies

Anybody can help me please.

On wich line did this error occur? Is your DGV initialized?

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.