Gautam Buddha Temple Varanasi,Varanasi - Buddhist Pilgrimage

Tuesday, March 6, 2012

How to get label or textbox control from .aspx page in .ascx user control page

 How to access controls from .aspx in .ascx user control page  
 Here i am showing a simple example how can we access controls from aspx in .ascx page  
 First i have created a WebUserControl.ascx user control page which contain a button.  
 WebUserControl.ascx page  
 <%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>  
       <asp:Button ID="btn_addUC" runat="server" Text="Add" OnClick="btn_addUC_Click" />  
 Write below code in code behind   
 WebUserControl.ascx.cs page  
 protected void btn_addUC_Click(object sender, EventArgs e)  
      Button btnSender = (Button)sender;  
      Page parentPage = btnSender.Page;      
      TextBox txt = (TextBox)parentPage.FindControl("txtName");  
      Label lbl = (Label)parentPage.FindControl("lblNAme");  
      lbl.Text = txt.Text;  
 Take a another test_page.aspx page and register the above user control in given below:  
 test_page.aspx page  
 <form id="form1" runat="server">  
           <uc1:WebUserControl runat="server" ID="WebUserControl" />  
           <asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />  
           <asp:Label ID="lblNAme" runat="server" Text="Label"></asp:Label>  
      Run and test the application.  
 Santosh Singh  

No comments:

Post a Comment