tags:

views:

67

answers:

2

I have a DateTime record in my table in a database and I write a query to get it from the database:

string command2 = "select Last_Modified from Company_Data where Company_Name='" + DescriptionEntryForm.SelectedItem.ToString() + "'";
SqlCommand search_company2 = new SqlCommand(command2, con_string.con);
SqlDataReader company_reader2 = search_company2.ExecuteReader();
dateform.Text = company_reader2.GetValue(0).ToString();
company_reader2.Close();

But the penultimate statement throw an exception saying "Invalid attempt to read when no data is present".

How can I solve it?

+6  A: 

Well, the immediate problem with your code is that you haven't called company_reader2.Read() to move the cursor onto the first row.

From the docs for SqlDataReader.Read:

The default position of the SqlDataReader is before the first record. Therefore, you must call Read to begin accessing any data.

You should also note the return value of Read() which indicates whether or not you've read to the end of the record set.

Other problems:

  • You should put using statements around the SqlCommand and SqlDataReader, otherwise if there's an exception you won't be closing the connection. You may be able to get away with disposing the command and letting the reader just disappear automatically - but I typically dispose of both just so I don't need to think too carefully.
  • You're assuming that the format of date/time will be appropriate by just calling ToString with no format specifier.
  • You should use a parameterised SQL query to avoid SQL injection attacks.
Jon Skeet
Listen to this man - you really need to address *all* these points, particularly the parametrised queries and `using` commands.
Dan Diplo
just company_reader2.Read(); is missing to move the cursor thanks
salamonti
@salamonti: Does your comment mean you're going to ignore the fact that you could easily leak database connections and leave yourself open to SQL injection attacks?
Jon Skeet
A: 

It looks like you've executed the command, but haven't actually read from it.

company_reader2 = search_company2.ExecuteReader();
if (company_reader2 != null && company_reader2.HasRows) {
    company_reader2.Read();
    dateform.Text = company_reader2[0].ToString();
}
Fosco
I don't believe `ExecuteReader` will ever return `null`. Personally I'd rather just use the return value of `Read()` instead of using `HasRows`, too. You've got to call it anyway, why not use it?
Jon Skeet
not need for if statement just company_reader2.Read();dateform.Text = company_reader2[0].ToString();thank you
salamonti
@salamonti And what happens if your reader doesn't return any rows?
Dan Diplo
it is in try catch if it doesn't return any thing mean that company not in the database and get me just error
salamonti
@Jon Skeet: thanks.. I learn something every day :)
Fosco