Click here to Skip to main content
15,895,538 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
so that if it is more than 2, the text color of two cells will change

but error
System.InvalidOperationException: 'Invalid attempt to read when no data is present.'


What I have tried:

<pre>SqlDataAdapter sda = new SqlDataAdapter("select Entry_Date,Received_Date from tblSaleServices", con);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            dataGridView1.DataSource = dt;


con.Open();
            Query = "select Entry_Date,Received_Date from tblSaleServices";
            SqlCommand cmd = new SqlCommand(Query, con);
            SqlDataReader sdr = cmd.ExecuteReader();

            DateTime entry = Convert.ToDateTime(sdr["Entry_Date"]);
            DateTime received = Convert.ToDateTime(sdr["Received_Date"]);

            TimeSpan value = received.Subtract(entry);
            int val = Convert.ToInt32(value);

            if (val > 2)
            {
                dataGridView1.DefaultCellStyle.ForeColor = Color.Red;
            }
            con.Close();
Posted
Updated 28-Jul-22 23:52pm

1 solution

The SqlDataReader is a reader class, which implies you need to actually run read operations on it before you can access any of the data returned from the SQL. That's exactly what your exception is telling you, you're attempting to read when there's nothing there to read yet.

Make sure you call sdr.Read() and check the result of this method (a boolean) before you try and access the data:
C#
// If you're only expecting one row:
if (sdr.Read()) {
  
}

// If you're expecting multiple rows:
while (sdr.Read()) {

}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900