在ASP.NET中使用多个DataReader的问题(C#)

时间:2011-06-08 05:57:36

标签: c# .net asp.net sql sqldatareader

SqlConnection conn1 = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");

SqlCommand COMM = new SqlCommand("select Role from Login where User_Name='admin'", conn1);
conn1.Open();

SqlDataReader reader = COMM.ExecuteReader();
while (reader.Read())
{
    string s = reader["Role"].ToString();
}
reader.Close();
conn1.Close();

SqlConnection conn = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");
SqlCommand comm = new SqlCommand("Select * from FileUpload where UploadedBy='"+NAME+"'",conn);

try
{
    conn.Open();

    SqlDataReader rdr = comm.ExecuteReader();
    if (s.Equals("admin"))
    {
        GridView1.DataSource = rdr;
        GridView1.DataBind();
    }

    if(s.Equals("teacher"))
    {
         GridView2.DataSource = rdr;
         GridView2.DataBind();
    }

    rdr.Close();
    //reader.Close();
}
catch
{
    conn.Close();
}

我在下面的连接中收到错误,说当前上下文中不存在s。如何使用多个数据加载器请帮助我。

2 个答案:

答案 0 :(得分:2)

宣布string s退出循环

  string s;
  while (reader.Read())
     {
         s = reader["Role"].ToString();
     }

答案 1 :(得分:1)

      SqlConnection conn1 = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");
      SqlCommand COMM = new SqlCommand("select Role from Login where User_Name='admin'", conn1);
      conn1.Open();
      SqlDataReader reader = COMM.ExecuteReader();
      string s = String.Empty;
      while (reader.Read())
          s = reader["Role"].ToString();