简体   繁体   中英

reader read multiple in one connection C#

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM