Reputation: 19
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?
Upvotes: 0
Views: 2491
Reputation: 360
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();
Upvotes: 1
Reputation: 138
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();
}
Upvotes: 0
Reputation: 36
Just to rule out the obvious, when you execute the sql statement "SELECT * FROM Table1 where name=depat" in Management Studio you get records returned?
Upvotes: 0