用sql数据填充GridView
问题描述:
我需要从我的用户表中选择具有我将必须从下拉列表中获得的roleID的用户的用户名。数据没有出现在GridView中。看不出有什么问题,请帮助我。 已经尝试过2种方式用sql数据填充GridView
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发生了什么,它说AutoGenerateColumns = false,我删除它。这一切都奏效了!
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();
}
+1
对不起,但我将不得不在这里更正你的答案Fel。要使用DataGrid是非常好的,你的代码容易受到SQL注入攻击,你可以通过用户输入连接一个查询字符串(DropDownList1的值),更多信息请查看:https://www.owasp.org/index.php/SQL_Injection – Ruben 2015-12-21 10:25:52
您是否尝试过调试?如果您直接通过对角色ID进行硬编码来运行查询,是否会得到任何结果? – 2014-12-05 03:36:02
我看不到任何连接字符串到数据库...简单的SQL命令是不够的。 – Yasskier 2014-12-05 03:36:25
'dt'实际上是否包含任何行? – 2014-12-05 03:36:54