Before reading this document, I would suggest you to go through following two articles
In this article, I will discuss how to use delegates and events. I will start with following figure
Generally if we create usercontrol, we create event and subscribed the event in our aspx page. To simplify, I will create one page that consists of two usercontrols. One usercontrol consists of list of categories and a button. Another usercontrol consists of a gridview to show the list of products related to selected category. We can do this in one page but to make you understand, I took this simple example and segregate it into two usercontrols.
I prefer to use dbml class for data access which will generate all the entities from database quickly. So I took Northwind database and Categories/Products table.
What we want to deliver is, user selects category from dropdownlist and click the button and it will show the list of products under the category in gridview. The important point is how we wiring up these twousercontrols and make them communicate between each other.
Let’s create first usercontrol.
The ascx code would be very simple like following
Collapse
<tr> <td align="left">Select Category <!–td> <td align="left"> <asp:DropDownList ID="ddlCategory"runat="server"AppendDataBoundItems="True"> <asp:ListItem Value="-1″>Select<!–asp:ListItem> <!–asp:DropDownList> <!–td> <td align="right"> <asp:Button ID="btnShow"runat="server"Text="ShowProducts"onclick="btnShow_Click"/><!–td> <!–tr> <!–table>
Come to code-behind for this.
First we will create one property that will get/set the listof categories.
Collapse
// Property to hold all the list ofCategories public IList<Category> ListOfCategory { get; set; } Then we set the Categorydropdownlist with this property on Page_Load event. protected void Page_Load(object sender, EventArgse) { try { if (!IsPostBack) { this.ddlCategory.DataSource =ListOfCategory; this.ddlCategory.DataTextField = "CategoryName"; this.ddlCategory.DataValueField = "CategoryID"; this.ddlCategory.DataBind(); } } catch (Exception exc) { Response.Write(exc.Message); } }
As in the code, if we set the ListOfCategory property andcall the Page_Load method, the dropdownlist box will be filled up with list ofcategories.
Now come to button click event. We will write one delegate,an event of type delegate and publish this event on the button_click event.This will cause to bind any method outside of this usercontrol but the prerequisite is to maintain the same method signature like defined delegate.Also before writing delegate, we will write a custom EventArgs class which will hold the selected category.
Collapse
public class SelectedCategoryEventArgs:EventArgs { public intSelectedCategory { get; set; } public SelectedCategoryEventArgs(int selectedCategory) { SelectedCategory = selectedCategory; } }
Next, we declare the delegate and an event of defined delegate type
Collapse
public delegate void _delegateShowProducts(object sender,SelectedCategoryEventArgse); public event _delegateShowProducts OnShowProducts;
After that, we publish this event on button_click event
Collapse
protected voidbtnShow_Click(object sender, EventArgs e) { try { OnShowProducts(this, new SelectedCategoryEventArgs(Convert.ToInt16( this.ddlCategory.SelectedValue))); } catch (Exceptionexc) { Response.Write(exc.Message); } }
That’s it. We completed the implementation of first usercontrol.
Now, we will create second usercontrol consists of gridviewonly, which will show the list of products based on selected category.
The ascx code would be very simple like
Collapse
<asp:GridView ID="grdProducts"runat="server"> <!–asp:GridView>
The code-behind willcontain one property which helps to get/set the list of products.
Collapse
public IList<Product> ListOfProducts { get; set; }
Next, we will define one method which will bind the ListOfProducts property with the gridview.
Collapse
public voidShowProducts() { try { this.grdProducts.DataSource =ListOfProducts; this.grdProducts.DataBind(); } catch (Exceptionexc) { Response.Write(exc.Message); } }
That’s it. We completed the implementation of second usercontrol.
Next task is to put thistwo usercontrols in aspx page. So the aspx code looks like
Collapse
<body> <form id="form1″ runat="server"> <div> <uc1:ucCategorySelectionID="ucCategorySelection1″runat="server"/> <!–div> <hr /> <div> <uc2:ucShowProducts ID="ucShowProducts1″runat="server"/> <!–div> <!–form> <!–body>
After that, we need to wire up two usercontrols. We will subscribe the event defined in button_click event of the first usercontrol with a method defined in second usercontrol using following code
Collapse
ucCategorySelection1.OnShowProducts+=new UserControls.ucCategorySelection._delegateShowProducts( ucCategorySelection1_OnShowProducts);
Remember to put this delegate declaration at page_load event so that everytime it will subscribe with the method. The method that will call by eventhandler, would contain following code
Collapse
public void ucCategorySelection1_OnShowProducts(objectsender,SelectedCategoryEventArgs e) { try { using (NorthwindDataContext_context = new NorthwindDataContext()) { var query = from_product in _context.Products where _product.CategoryID == e.SelectedCategory select _product; IList<Product>_products = query.ToList<Product>(); ucShowProducts1.ListOfProducts = _products; ucShowProducts1.ShowProducts(); } } catch (Exceptionexc) { Response.Write(exc.Message); } }
In the above code, we are getting the selected category from SelectedCategoryEventArgs class and pass this categoryID in LINQ to SQL query to get the list of products. Then we set the ListOfProducts property to set the list of products and call the ShowProducts methods which will bind the gridview.
Next task is to set thelist of category. We will use following code
Collapse
protected void Page_Load(object sender, EventArgse) { if (!IsPostBack) { using (NorthwindDataContext_context = new NorthwindDataContext()) { var query = from_category in _context.Categories select _category; IList<Category>_categories = query.ToList<Category>(); ucCategorySelection1.ListOfCategory = _categories; } } }
The above code will bring list of categories and set it through ListOfCategory property.
That’s it. We are done.In summary, we are getting list of categories which we set through a property.Now at first usercontrol’s page_load event, the category dropdownlist populates. Then when we click on button, an eventhandler associated with theevent will fire, which brings the list of products and bind the product list with gridview.
In the above example,you never find any dependency in the code. In order to run the example, youneed to have SQL Server Northwind database in your machine and update the web.config with your connectionstring.
Collapse
<connectionStrings> <add name="NorthwindConnectionString"connectionString="DataSource=.\sqlexpress; Initial Catalog=Northwind;Integrated Security=True"providerName="System.Data.SqlClient"/> <!–connectionStrings>
No comments:
Post a Comment