简体   繁体   中英

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 .

My webform1.aspx page contains a drop-down list, Gridview and SqlDatasource .

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

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

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

i believed Ruly got the answers=)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM