且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在asp.net c中使用多个sqldatareader时出错

更新时间:2023-10-15 22:07:28

看看你的代码:

Look at your code:
rd.Close();
 SqlDataReader rd1 = cmd1.ExecuteReader();

 if (rd1.Read())
 {
     clg_lbl.Text = "College " + " " + rd.GetString(2);
     uni_lbl.Text = "University  " + rd.GetString(8);
    abt_lbl.Text = "About me:" + " " + rd1.GetString(4);
    crnt_lbl.Text = rd.GetString(4);
    btch_lbl.Text = "Batch  " + rd.GetString(9) + " - " + rd.GetString(10);
 }

因为你关闭了 rd 我怀疑你想要使用 rd1 而不是...



这是使用块真正有用的情况之一:

Since you have closed rd I suspect you wanted to use rd1 instead...

This is one of the cases where a using block really helps:

using (SqlDataReader rd = cmd.ExecuteReader())
{
    if (rd.Read())
    {

        unm_lbl.Text = rd.GetString(0) + "  " + rd.GetString(1);
        frm_lbl.Text = rd.GetString(7);


        bdt_lbl.Text = rd[11] + " " + rd[13];
        age_lbl.Text = rd[14].ToString();
        eml_lbl.Text = rd.GetString(15);
    }
}

意味着 rd 在使用结束时超出范围,编译器会发出错误信息。

Means that rd goes out of scope at the end of it''s use, and the compiler would have issued an error message.


你用rd.Close()关闭了DataReader;只需将其打开直到结束,并在关闭rd1时将其关闭。您正试图从if(rd1.Read())语句下的rd读取以获得College。
You closed the DataReader with rd.Close(); Just leave it open until the end and close it when you close rd1. You are trying to read from rd under the if (rd1.Read()) statement to get College.