I am trying to display the data using parametrized query
try
{
SqlConnection xconn = new SqlConnection();
xconn.ConnectionString = @" Data Source=servername; Database=master; Trusted_Connection=yes ";
xconn.Open();
SqlCommand ycmd = new SqlCommand ("select * from tablename where column1 = @name", xconn);
ycmd.Parameters.Add("@name", dropdownlist.SelectedValue);
SqlDataAdapter da = new SqlDataAdapter(s,xconn);
SqlCommandBuilder cmdbuilder = new SqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
gridview.DataSource = dt;
gridview.DataBind();
}
catch(Exception ex)
{
label.Text = ex.Message + "\n" + ex.StackTrace;
}
How do I get it to work?
Try this:
You don’t need to call
SqlConnection.Open()when you are using theSqlDataAdapter.Fill()method. In that method it opens up the connection and disposes/closes it when complete. (this isn’t the problem, just an FYI)The way you created your
SqlDataAdapteris the problem. You didn’t create it with theSqlCommandas a constructor, just the command text. Because of that, you didn’t pass in the parameter that was specified in theSqlCommandclass.Let me know if that works. And if that doesn’t work, try manually running this query in SSMS to ensure that it actually returns a result set. Also, make sure that your
ListControl.SelectedValueproperty contains something. Do this by debugging and analyze what is stored there.