C# – DataReader is null or empty


Using C#

I have a datareader that return a lsit of records from a mysql database.

I am trying to write code that checks if the datareader isnull. The logic behind this is: If the datareader having field then display the info otherwise hide the field.

I have tried:

cmd1 = new OdbcCommand("Select * from tb_car where vehicleno = '" + textbox2.text  + "';", dbcon);
        dr1 = cmd1.ExecuteReader();

if (dr1["tb_car"]. != DBNull.Value) 
    textbox1.Text  = "contains data"; 
    textbox1.Text = "is null"; 

The above code gives me this error:

Exception Details: System.IndexOutOfRangeException: Additional

Any help would be greatly appreciated…

Best Solution

I see a few problems here... First, it looks like you're trying to access the table name in the line:

if(dr1["tb_car"] != DBNull.Value

You should be passing a FIELD NAME instead of the table name. So if the table named "tb_car" had a field called CarId, you would want to have your code look like:

if(dr1["CarId"] != DBNull.Value)

If I'm right, then there is probably no field named "tb_car", and the Index is Out of Range error is because the DataReader is looking for an item in the column collection named "tb_car" and not finding it. That's pretty much what the error means.

Second, before you can even check it , you have to call the DataReader's Read() command first to read a line from the database.

so really your code should look like...

   if(dr1["CarId"] != DBNull.Value)

and so on.

See here for the proper use of a DataReader: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.read.aspx

Finally, if you're just checking to see if there are any rows in the table, you can ignore all of the above and use the HasRows property as in


although if you're using the while(dr.Read()) syntax, the code in the while loop will only execute if there are rows in the first place, so the HasRows could potentially be unnecessary if you don't want to do anything with no results. You would still want to use it if you want to return a message like "no results found", of course..

Edit - Added

I think there's a problem also with the line

if(dr1["CarId"] != DBNull.Value)

You should be using if DataReader's IsDbNull() method. as in


Sorry I missed that the first time around.