Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 获取数据读取器的错误_C# - Fatal编程技术网

C# 获取数据读取器的错误

C# 获取数据读取器的错误,c#,C#,我试图使用datareader从sql数据库获取数据,并将其放入组合框中,但我得到的错误代码是:当reader关闭时调用Read的尝试无效。 错误在while语句中代码的第二部分。它是表单加载的代码 class DataLoad { public SqlDataReader comboboxLoad() { SqlConnection con = new SqlConnection("Data Source=Abdullah-PC;Initial Catalo

我试图使用datareader从sql数据库获取数据,并将其放入组合框中,但我得到的错误代码是:当reader关闭时调用Read的尝试无效。 错误在while语句中代码的第二部分。它是表单加载的代码

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
。或者……这将更有意义,但我认为如果保持相同的结构,它会突出显示原始代码的错误。