difurious difurious - 1 month ago 17
C# Question

C# no data returned from database - "Invalid attempt to read when no data is present"

I am try to display data from a database. However even though data exists in the database no records are being returned.

If run the following query:

select Id, Movie_Name from [MovieTable] where Movie_Name like '10,000 BC'


I get being returned:

enter image description here

However when running a similar query in c# nothing seems to be being returned. My code is as follows:

try
{
string query = "select * from [MovieTable] where Movie_Name like @MovieName";
string movieName = "10,000 BC"

using (SqlConnection sconnection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=E:\Application\ApplicationDatabase.mdf;Integrated Security=True");)
using (SqlCommand command = new SqlCommand(query, sconnection))
{
sconnection.Open();
command.Parameters.AddWithValue("@MovieName", movieName);

using (SqlDataReader oReader = command.ExecuteReader())
{
if (oReader != null)
{
while (oReader.Read())
{
MessageBox.Show(oReader["Movie_Name"].ToString());
}
}
}
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}


The message box never appears. Adding a third message box just above oReader.Read() displays the message "Invalid attempt to read when no data is present". Is there something i am missing?

Answer

Issue was with the data itself. Field was incorrectly set as type "Text". I altered the fields data type to "nvarchar(MAX)". It also mean't the query could be altered to:

"select * from [MovieTable] where Movie_Name = @MovieName"
Comments