0

我想根据下拉列表从数据库中选择值。我的数据库包含具有字段值的表: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();
}

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

4

3 回答 3

1

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? 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 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();
于 2013-03-22T01:19:20.257 回答
0

我相信 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();
}
于 2013-03-22T02:50:16.040 回答
0

只是为了排除明显的情况,当您在 Management Studio 中执行 sql 语句“SELECT * FROM Table1 where name=depat”时,您会返回记录吗?

于 2013-03-22T01:23:07.553 回答