您好我一直在为项目创建订单表单,并且难以将日期编号输入到数据行。我有以下代码,但我收到错误'ExecuteReader需要一个开放和可用的连接。连接的当前状态已关闭。'。任何有关这方面的帮助将不胜感激。
private void cmbSelectDay_SelectedIndexChanged(object sender, EventArgs e)
{
//variable for case statement
int day = 0;
string Sql = "Select deliveryDayNo from standardOrderDetails order by deliveryDayNo";
SqlConnection conn = new SqlConnection(connStr); // ...
SqlCommand cmd = new SqlCommand(Sql, conn); //there is an error happening here that im not too sure about that would need to be fixed first. but once its fixed this should all work.
SqlDataReader DR = cmd.ExecuteReader();
while (DR.Read())
{
cmbSelectDay.Items.Add(DR[0]);
}
//case statement to take the selected value of the combo box and assign a new value to the variable "day" acordingly.
switch(cmbSelectDay.SelectedText.ToString())
{
case "Monday":
{
day = 1;
break;
}
case "Tuesday":
{
day = 2;
break;
}
case "Wednesday":
{
day = 3;
break;
}
case "Thursday":
{
day = 4;
break;
}
case "Friday":
{
day = 5;
break;
}
case "Saturday":
{
day = 6;
break;
}
}
// DataRow dr = dsLeprechaun.Tables["standardOrderDetails"].Rows.Find(day);
DataRow dr = dsLeprechaun.Tables["standardOrderDetails"].Rows.Find(day.ToString());
dgvOrder.Rows.Add(dr["deliveryDayNo"].ToString());
lblSelectCategory.Visible = true;
lstBoxSelectCategory.Visible = true;
}
答案 0 :(得分:1)
所以......打开连接:
using(SqlConnection conn = new SqlConnection(connStr))
using(SqlCommand cmd = new SqlCommand(Sql, conn))
{
conn.Open();
using(SqlDataReader DR = cmd.ExecuteReader())
{
// consume data
}
}
您可能还想查看有助于ADO.NET的工具,例如" dapper" - 例如,如果我假设这个数据是一个字符串,我们可以将所有这些缩短为:
using(SqlConnection conn = new SqlConnection(connStr))
{
var days = conn.Query<string>(
"Select deliveryDayNo from standardOrderDetails order by deliveryDayNo"
).ToList();
// now add the items from "days"
}
答案 1 :(得分:0)
在调用conn
方法之前,您需要打开连接对象ExecuteReader()
。
试试这个:
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(Sql, conn);
conn.Open(); //Add this statement
SqlDataReader DR = cmd.ExecuteReader();
答案 2 :(得分:0)
你必须打开连接
conn.Open();
using(SqlDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
{
//code here
}
}