Reputation: 395
In my database table I have two columns: pagename
and pageinfo
. I want to retrieve data when I pass in pagename
. I use code which I got from Stackoverflow today but some issue in code throws an error:
An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code.Additional information: Invalid attempt to read when no data is present.)
This is the code:
public string GetPageInfo(string filenames)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=.;Integrated Security=True");
con.Open();
SqlCommand command = new SqlCommand("Select pageinfo from T_Pages where pagename=@filenames", con);
command.Parameters.AddWithValue("@filenames", filenames);
// int result = command.ExecuteNonQuery();
using (SqlDataReader reader = command.ExecuteReader())
{
return reader["pageinfo"].ToString(); ;
}
// return string GetPageInfo;
}
Upvotes: 0
Views: 59
Reputation: 5899
This is because of this:
return reader["pageinfo"].ToString();
if reader["pageinfo"] is null, then ToString() will throw an exception.
Replace above line with this:
if(reader["pageinfo"] != null)
{
return reader["pageinfo"].ToString();
}
else
{
return "";
}
Or using Null-conditional Operators:
return reader["pageinfo"]?.ToString();
EDIT
You also need to add Read() before return:
reader.Read();
return reader["pageinfo"]?.ToString();
Upvotes: 2