[英]Select data from database based on drop-down list not working
I want to select values from the database based on a drop-down list. 我想基于一个下拉列表从数据库中选择值。 My database contains tables with fields values:
id(primary key),name,fullname,depat
. 我的数据库包含具有以下字段值的表:
id(primary key),name,fullname,depat
。
My webform1.aspx
page contains a drop-down list, Gridview
and SqlDatasource
. 我的
webform1.aspx
页面包含一个下拉列表Gridview
和SqlDatasource
。
This is my Webform1.aspx.cs
code: 这是我的
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();
}
No data is shown after selecting values from the drop-down list. 从下拉列表中选择值后,没有数据显示。 Where is the error?
错误在哪里?
Reading from your code, what you want to do is fill GridView1 with data from Table1 where name=depat , is it really what you wants? 从您的代码中读取,您要做的是用Table1中name = depat的数据填充GridView1 ,这真的是您想要的吗? Maybe you can make it clearer on what you want.
也许您可以更清楚地说明您想要的内容。
If you want to get the data based on the selected value, then you should make it: 如果要基于所选值获取数据,则应使其:
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Table1 where name='" + s + "'", con);
But I strongly suggest you use Parameterized Query, create a SqlCommand first 但我强烈建议您使用参数化查询,首先创建一个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);
EDIT: 编辑:
If you want to get all the data for a specific department: 如果要获取特定部门的所有数据:
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();
只是为了排除明显的情况,当在Management Studio中执行sql语句“ SELECT * FROM Table1 where name = depat”时,会返回记录吗?
i believed Ruly got the answers=) 我相信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 name=@name", con);
cmd.Parameters.Add("@name", s);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.