从下拉列表中选择不符合数据的数据
我想根据下拉列表从数据库中选择值。我的数据库包含具有字段值的表格:id(primary key),name,fullname,depat
。从下拉列表中选择不符合数据的数据
我的webform1.aspx
页面包含一个下拉列表,Gridview
和SqlDatasource
。
这是我的Webform1.aspx.cs
代码:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string s = DropDownList1.SelectedValue.ToString();
SqlConnection con = new SqlConnection(
ConfigurationManager.ConnectionStrings["ztvConnectionString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Table1 where name=depat", con);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
没有数据从下拉列表中选择值后显示。错误在哪里?
从您的代码阅读,你想要做的就是填写GridView1从表1数据,其中名= depat,真的是你想要什么?也许你可以更清楚地表达你想要的东西。
如果你想获得基于所选值的数据,那么你应该做它:
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Table1 where name='" + s + "'", con);
但我强烈建议你使用参数化查询,创建一个SqlCommand第一
SqlCommand cmd = new SqlCommand("SELECT * FROM Table1 WHERE name = @name", conn)
cmd.Parameters.Add("@name", SqlDbType.NVarChar);
cmd.Parameter["@name"].Value = s;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
编辑:
如果你想获得特定部门的所有数据:
string s = DropDownList1.SelectedValue.ToString();
//SqlConnection...
SqlCommand cmd = new SqlCommand("SELECT * FROM Table1 WHERE depat = @depat", conn)
cmd.Parameters.Add("@depat", SqlDbType.NVarChar);
cmd.Parameter["@depat"].Value = s;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
感谢您的Response.My的目标是,当在下拉列表中选择部门时,GridView只显示ID,姓名,全名属于该部门。 – rogerkp 2013-03-22 13:34:22
我想卢伊已经提出了一个你的问题的答案。您正在从右下角的字符串中的下拉列表中存储选定的值。所以如果现在您已经从dropdownlist中选择了depat,那么Ruly的查询会为您提供属于该depat的数据。 – 2013-06-25 14:15:48
只是为了排除显而易见的情况,当您在Management Studio中执行sql语句“SELECT * FROM Table1 where name = depat”时,您会得到记录吗?
我相信Ruly得到了答案=)
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string s = DropDownList1.SelectedValue.ToString();
SqlConnection con = new SqlConnection(
ConfigurationManager.ConnectionStrings["ztvConnectionString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Table1 where [email protected]", con);
cmd.Parameters.Add("@name", s);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
你实际上得到一个错误,或者你只是没有得到预期的效果?是否有将选定值保存为's'的理由?它没有在我看到的其他事件处理程序中使用。 – 2013-03-22 01:05:48