populating GridView with sql data

余生颓废 提交于 2019-12-13 08:15:35

问题


I need to select from my users table the username of the user that has the roleID that I will have to get from the dropdownlist. The data are not appearing in the GridView. Can't see what's wrong, help me please. Already tried 2 ways

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
   {
       SqlConnection con = new SqlConnection(cs);
       con.Open();
       SqlCommand cmd = new SqlCommand("select username from tblUser where roleID like '" + DropDownList1.SelectedValue + "'", con);

       SqlDataAdapter da = new SqlDataAdapter(cmd);
       DataTable dt = new DataTable();
       da.Fill(dt);
       GridView2.DataSource = dt;
       GridView2.DataBind();
       con.Close();
   }

protected void Button2_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(cs);
    con.Open();
    SqlCommand cmd = new SqlCommand("select username from tblUser where roleID like '" + DropDownList1.SelectedValue + "'", con);

    SqlDataReader reader = cmd.ExecuteReader();

    GridView2.DataSource = reader;
    GridView2.DataBind();
    con.Close();
}

回答1:


Okay, so this one worked for me. And you also must check the sources. Like what happened to my GridView, it says AutoGenerateColumns = false, I removed it. And it all worked!

protected void Button2_Click(object sender, EventArgs e)
{
    string cs = ConfigurationManager.ConnectionStrings["roleDB"].ConnectionString;
    SqlConnection con = new SqlConnection(cs);
    con.Open();
    SqlCommand cmd = con.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "select username from tblUser where roleID like '" + DropDownList1.SelectedValue + "'";
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    GridView2.DataSource = dt;
    GridView2.DataBind();
    con.Close();
}


来源:https://stackoverflow.com/questions/27308276/populating-gridview-with-sql-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!