簡體   English   中英

讀取器讀取多個連接C#

[英]reader read multiple in one connection 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());
    }
}

當我運行它時,它假設使用textBox來獲取entry_(在這種情況下,假設3),然后從我的sql表中選擇列,並填寫崩潰的其他文本框

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: 

當我將每個單獨分離到自己的sql連接時,它工作正常,但我想知道是否可以合並為一個。

我的桌子看起來像entry_ | 3實體| NAME shop_order | NUMBERS小時_ | 1個工作日期| 01/01/0001

我對C#相當陌生,我做了一些研究,但找不到。

用括號將您的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循環僅運行第一行,而while循環結束時,其他行運行。 因此發生異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM