繁体   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