Reputation: 3
I have this code snippet
using (SqlConnection connection = new SqlConnection(Properties.Settings.Default.WPC_AppConnectionString))
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT engid,shop_order,hours_,work_date FROM engineer WHERE entry_=" + textBox2.Text.ToString();
connection.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
textBox4.Text = reader["engid"].ToString();
textBox6.Text = reader["shop_order"].ToString();
textBox8.Text = reader["hours_"].ToString();
dateTimePicker3.Value = Convert.ToDateTime(reader["work_date"].ToString());
}
}
When I run this its suppose to use a textBox to get entry_ ( in this case lets say 3) Then select the columns from my sql table and fill out the other textboxes it crashes with
System.InvalidOperationException occurred
HResult=-2146233079
Message=Invalid attempt to read when no data is present.
Source=System.Data
StackTrace:
at System.Data.SqlClient.SqlDataReader.CheckDataIsReady(Int32 columnIndex, Boolean allowPartiallyReadColumn, Boolean permitAsync, String methodName)
InnerException:
It works fine when i separate each one out to its own sql connection but I was wondering if I can combine into one.
my table looks like entry_ | 3 engid | NAME shop_order | NUMBERS hours_ | 1 work_date | 01/01/0001
I'm fairly new to C# and i did some research but couldn't quite find this.
Upvotes: 0
Views: 66
Reputation: 3600
Surround your while statement with braces like this.
while (reader.Read())
{
textBox4.Text = reader["engid"].ToString();
textBox6.Text = reader["shop_order"].ToString();
textBox8.Text = reader["hours_"].ToString();
dateTimePicker3.Value = Convert.ToDateTime(reader["work_date"].ToString());
}
because in your case while loop runs only first line and when while loop ends the other lines run. so the exception occurs.
Upvotes: 1