我有这段代码
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 engid |名称 shop_order | NUMBERS hours_ | 1 work_date | 01/01/0001
我对C#很新,我做了一些研究,但却找不到这个。
答案 0 :(得分: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循环只运行第一行,而while循环结束时其他行运行。所以发生异常。