数据阅读器出错

时间:2013-12-11 12:49:31

标签: c#

我正在尝试使用datareader从sql数据库中获取数据以将它们放入组合框中但是在此代码中出现错误时说:读取器关闭时无效尝试调用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"]);
        }
    }

2 个答案:

答案 0 :(得分:2)

您已使用此行关闭了您的连接:con.Close()

在完成阅读之前,您需要保持打开状态。尝试使用using声明:

// 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();
}

答案 1 :(得分:0)

问题是,您正在关闭函数con.Close();中的连接comboboxLoad()。读者需要与数据库建立开放连接才能工作。

放置dataReader后应关闭连接。