2016-05-09 1 views
0

が、私はこのコードスニペットを持っている一つの接続C#で複数の読み読者は

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()); 
    } 
} 

私は実行すると、このそのそれから私のSQLから列を選択します(この場合は3を言うことができますに)entry_を取得するためにテキストボックスを使用すると仮定テーブルとは、私は、独自のSQL接続のうち各1を分けるが、私は一つに結合することができる場合、私は思っていたとき、それは正常に動作します

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: 

でそれがクラッシュし、他のテキストボックスに必要事項を記入します。

私のテーブルは のように見えます。 3 engid |名前 shop_order | NUMBERS hours_ | 1 work_date | 01/01/0001

私はかなりC#の新人です。私はいくつかの調査をしましたが、これを見つけることができませんでした。

答えて

1

while文をこのような中括弧で囲みます。

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()); 

} 

あなたのケースではループが最初の行のみを実行し、whileループが終了すると他の行が実行されるためです。例外が発生します。

+0

うわー....それは感謝しました。 –