我想通过TEXTBOX输入ID查询信息,查询不到时显示一个查无此人,查询正确时通过GRIDVIEW显示出来。
下面程序是错误的  有两个连接数据库的操作
所以我想问下大家到底该怎么写  dataReader和dataAdapter都要连接数据库 我不知道怎么搞了
protected void Button6_Click(object sender, EventArgs e)
    {
        try
        {
            sql = new SqlConnection(str);
            sql.Open();
            string sel = "select * from isa where id='" + TextBox1.Text.ToString().Trim() + "'";
            SqlCommand cmd = new SqlCommand(sel, sql);
            SqlDataReader sdr= cmd.ExecuteReader();
            if (sdr.Read()==false)
            {
                Response.Write("<script language=javascript>alert('查无此人')</script>");
            }
             SqlDataAdapter sda =new SqlDataAdapter(sel,sql);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            GridView2.DataSource = dt;
            GridView2.DataBind();
            
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            sql.Close();
        }    }

解决方案 »

  1.   


     sql = new SqlConnection(str);
      //sql.Open();//连接不用打开
      string sel = "select * from isa where id='" + TextBox1.Text.ToString().Trim() + "'";
      
      SqlDataAdapter sda =new SqlDataAdapter(sel,sql);
      DataTable dt = new DataTable();
      int count = sda.Fill(dt);
      if(count == 0)
      {
      Response.Write("<script language=javascript>alert('查无此人')</script>");
      }
      else
      {
         GridView2.DataSource = dt;
         GridView2.DataBind();
      }
    这样呢? 
      

  2.   

    为什么连接不用打开也能连到GRIDVIEW并让他显示?