为了账号安全,请及时绑定邮箱和手机立即绑定

已经有一个与此命令关联的打开的 DataReader

已经有一个与此命令关联的打开的 DataReader

C#
暮色呼如 2022-07-10 10:10:24
我创建了 3 个下拉列表,我想按学生姓名、父亲姓名或序列号进行搜索。当我选择学生姓名或父亲姓名并写下姓名时,它会显示数据。但是当我选择“按序列号”搜索时,出现错误:已经有一个DataReader与此命令关联的打开,必须先关闭。错误代码搜索截图我试图关闭 dataReader 但它不起作用。protected void btnSearch_Click(object sender, EventArgs e){        string QueryStudent = "Select SerialNumber as [Serial No.], Name as [Student Name], FatherName as Father,Phone,Course, AdmissionDate as[Admission date], Status from tblStudents where Name= '" + txtSearch.Text + "'";        string QueryFather = "Select SerialNumber as [Serial No.], Name as [Student Name], FatherName as Father,Phone,Course, AdmissionDate as[Admission date], Status from tblStudents where FatherName= '" + txtSearch.Text + "'";        string QuerySerial = "Select SerialNumber as [Serial No.], Name as [Student Name], FatherName as Father,Phone,Course, AdmissionDate as[Admission date], Status from tblStudents where SerialNumber= '" + txtSearch.Text + "'";        con.Open();        using (var sqlCommand = new SqlCommand(QueryStudent, con))        using (var sqlCommand2 = new SqlCommand(QueryFather, con))        using (var sqlCommand3 = new SqlCommand(QuerySerial, con))        {            SqlDataReader reader = sqlCommand.ExecuteReader();            if (DropDownList.SelectedItem.Value == "By Student Name")            {                if (!reader.HasRows)                {                    GrindSearch.Visible = false;                    lblmsg.Visible = true;                    lblmsg.Text = "No Record found";                }
查看完整描述

2 回答

?
犯罪嫌疑人X

TA贡献2080条经验 获得超4个赞

您可以通过将 MultipleActiveResultSets=true 添加到连接字符串的提供程序部分来解决此问题。



查看完整回答
反对 回复 2022-07-10
?
冉冉说

TA贡献1877条经验 获得超1个赞

"By Serial Number"子句不以相同的reader.Close();开头"By Father Name"

但更一般地说,您对该读者的管理是脆弱的。
它应该在一个using(...) {...}块中管理。

而且,相关的,算法结构看起来远非高效。当DropDownList.SelectedItem.Value == "By Serial Number"您已经执行了 QueryStudent 时,永远不要使用它的结果。


查看完整回答
反对 回复 2022-07-10
  • 2 回答
  • 0 关注
  • 88 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号