C# 根据下拉列表“不工作”从数据库中选择数据

C# 根据下拉列表“不工作”从数据库中选择数据,c#,.net,database,C#,.net,Database,我想根据下拉列表从数据库中选择值。我的数据库包含具有以下字段值的表:id(主键)、name、fullname、depat 我的webform1.aspx页面包含一个下拉列表,Gridview和SqlDatasource 这是我的Webform1.aspx.cscode: protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { string s = DropDownList1.Selec

我想根据下拉列表从数据库中选择值。我的数据库包含具有以下字段值的表:
id(主键)、name、fullname、depat

我的
webform1.aspx
页面包含一个下拉列表,
Gridview
SqlDatasource

这是我的
Webform1.aspx.cs
code:

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();
}

从下拉列表中选择值后,不会显示任何数据。错误在哪里?

从代码中读取,您要做的是使用表1中的数据填充GridView1,其中name=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();

为了排除显而易见的问题,当您在ManagementStudio中执行sql语句“SELECT*FROM Table1 where name=depat”时,您会得到返回的记录?

我相信Ruly得到了答案=)


你是真的犯了错误,还是没有得到预期的结果?是否有理由将所选值保存到
s
?我看到的事件处理程序的其余部分没有使用它。感谢您的回复。我的目标是,当在下拉列表中选择dept时,GridView仅显示id、名称和全名,这些信息仅属于该dept。我想Ruly已经建议了您问题的答案。您将从下拉列表中选择的值存储在字符串的右侧。因此,如果现在您已经从dropdownlist中选择了depat,那么Ruly的查询将返回属于该depat的数据。
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();
}