2. Drag the GridView control to a design surface
3. Enable the "AutoPostBack" attribute on the "DropDownList1" control, by clicking on the "Source" tab then add the following line
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true">4. In the code behind add the BindGridView method
</asp:DropDownList>
protected void BindGridView(int catId)The method above takes an int parameter call "catId" based on the parameter being passed in we query the "Products" table based on the value being passed in. There is a @CategoryID in the SqlCommand, that is a placeholder for an SqlParameter that we will have to create and add to the SqlCommand later. The @CategoryID SqlParamter takes the value of the catId. 5. In the Page_Load method we have to call the BindGridView method
{
DataTable dtProducts = new DataTable();
string connectString = WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectString))
{
SqlCommand cmd = new SqlCommand("SELECT DISTINCT ProductID,ProductName,UnitPrice,UnitsInStock "
+ "FROM Products " + " WHERE Products.CategoryID = @CategoryID", conn);
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "CategoryID";
parameter.SqlDbType = SqlDbType.Int;
parameter.Value = catId;
cmd.Parameters.Add(parameter);
conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dtProducts);
GridView1.DataSource = dtProducts;
GridView1.DataBind();
}
}
protected void Page_Load(object sender, EventArgs e)Notice in the code above we have to call the BindGridView method twice. Once when the page first loads, it will take the default selection which is "Seafood" then on subsequent page loads it will take the user's selection to populate the GridView control.
{
if(!Page.IsPostBack)
{
BindCategoriesList();
SetDefaultSelectItem("Seafood");
BindGridView(Convert.ToInt32(DropDownList1.SelectedValue));
}
else
{
BindGridView(Convert.ToInt32(DropDownList1.SelectedValue));
}
}
Related Blogs:
- Bind a DataTable To A DropDownList
- (DropDownList) Setting Default Value on First Page Load
- Use The DropDownList Control To Populate GridView
- Bind DropDownList To A List Of Objects
No comments:
Post a Comment