Friday, May 25, 2012

Interaction between two user controls in asp net c#.Net


  Create 2 tables in the DB 1. companies and  2. products

  Create 2 user controls
a)      one with dropdownlist name as UCDDL.ascx
b)      two with gridview name as UCGV.ascx
2.      In  ucddl.ascx drag and drop dropdownlist name it as ddlcountries
3.      Bind the companies table to dropdownlist as shown in example (page load event)
4.      Create an event globally as below
public event EventHandler CountryName;


5.  Double click on dropdownlist and set AutoPostBack="true"
6.  In the selected Index Changed event write these two lines

Session["conseltd"] = ddlcountries.SelectedValue.ToString();
CountryName(this,EventArgs.Empty);
7.  Dropdown usercontrol is completed.
8.  In UCGV.ascx drag and drop a gridview and name it as GridView1
9.  Bind the gridview in the pageload event according to selected company as shown below.

SqlConnection con = new SqlConnection(constring);
string country = Session["conseltd"].ToString();
if (country != "<--Select-->")
 {
  DataSet ds = new DataSet();
  SqlDataAdapter da = new SqlDataAdapter("select * from products where cid='" + country + "'",  con);
  da.Fill(ds, "products");
  GridView1.DataSource = ds;
  GridView1.DataBind();
 }
 else
 {
  GridView1.DataSource = "";
  GridView1.DataBind();
 }

10. Up to now we completed two user controls.
11. Now the amain part is to communication between these two controls.
12. Now drag and drop UCDDL.ascx on to the default.aspx page, it will be automatically registered as follows.
<%@ Register src="UCDDL.ascx" tagname="UCDDL" tagprefix="uc1" %>
13. See the image below image

























1.  Select user control and press CTRL+SpaeBar you can see the event you created un that page as shon above
2.  Paste as below <uc1:UCDDL ID="UCDDL1" runat="server" OnCountryName="selectedCountry"/>
3.  Now drag and drop a panel on to page
4.  In default.aspx.cs page create an event with this name selectedCountry as shown below
        protected void selectedCountry(object sender, EventArgs e)
        {
            pnlgrid.Controls.Add(LoadControl("~/UCGV.ascx"));
        }
5.  Press F5 and select dropdownlist

























  Download source code from Here

No comments:

Post a Comment