C# 获取数据读取器的错误
我试图使用datareader从sql数据库获取数据,并将其放入组合框中,但我得到的错误代码是:当reader关闭时调用Read的尝试无效。 错误在while语句中代码的第二部分。它是表单加载的代码C# 获取数据读取器的错误,c#,C#,我试图使用datareader从sql数据库获取数据,并将其放入组合框中,但我得到的错误代码是:当reader关闭时调用Read的尝试无效。 错误在while语句中代码的第二部分。它是表单加载的代码 class DataLoad { public SqlDataReader comboboxLoad() { SqlConnection con = new SqlConnection("Data Source=Abdullah-PC;Initial Catalo
class DataLoad
{
public SqlDataReader comboboxLoad()
{
SqlConnection con = new SqlConnection("Data Source=Abdullah-PC;Initial Catalog=SmartPharmacyDB;Integrated Security=True");
SqlCommand com = new SqlCommand();
com.Connection = con;
SqlDataReader dr;
com.CommandText = "select drugname from drugtab order by drugname";
con.Open();
dr = com.ExecuteReader();
con.Close();
return dr;
}
}
private void Smart_Pharmacy_Load(object sender, EventArgs e)
{
DataLoad d = new DataLoad();
SqlDataReader DR = d.comboboxLoad();
while (DR.Read())
{
DrugNameCombo.Items.Add(DR["drugname"]);
}
}
您关闭了与此行的连接:
con.Close()
你需要把它打开,直到你读完为止。尝试使用和语句:
// Open your connection here
SqlConnection con = new SqlConnection("Data Source=Abdullah-PC;Initial Catalog=SmartPharmacyDB;Integrated Security=True");
con.Open();
// The using statement declares that you want to use the SqlDataReader for a certain
// block of code. Can be used because it implements IDisposable
using(SqlDataReader DR = d.comboboxLoad(con)) {
while (DR.Read())
{
DrugNameCombo.Items.Add(DR["drugname"]);
}
}
// When we reach here, the SqlDataReader will be disposed
// Could do some more work here
// Finally close the connection
con.Close();
您需要更新您的comboboxLoad
,以支持这种新的工作方式
public SqlDataReader comboboxLoad(SqlConnection con)
{
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandText = "select drugname from drugtab order by drugname";
return com.ExecuteReader();
}
问题是,您正在关闭连接con.Close()代码>在函数中comboboxLoad()
。读取器需要与数据库的开放连接才能工作
您应该在处理完dataReader后关闭连接。方法comboboxLoad
是多余的。至少您还应该添加将项目添加到组合框的代码。这将修复错误并验证方法的名称。或者简单地移动DrugNameCombo.Items。将-code添加到ComboxLoad
方法并使其void
。或者……这将更有意义,但我认为如果保持相同的结构,它会突出显示原始代码的错误。