使用 SQL 数据填充网格视图
本文关键字:网格 视图 填充 数据 SQL 使用 | 更新日期: 2023-09-27 18:33:20
我需要从我的用户表中选择具有角色ID的用户的用户名,我必须从下拉列表中获取该角色ID。数据未显示在网格视图中。看不出有什么问题,请帮帮我。已经尝试了 2 种方式
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();
}
好的
,所以这个对我有用。您还必须检查来源。就像我的 GridView 发生了什么一样,它说自动生成列 = 假,我删除了它。这一切都奏效了!
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();
}