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" %>
<table>
<tr>
<td>
<asp:Button ID="btn_addUC" runat="server" Text="Add" OnClick="btn_addUC_Click" />
</td>
</tr>
</table>
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 it.as given below:
test_page.aspx page
<form id="form1" runat="server">
<div>
<uc1:WebUserControl runat="server" ID="WebUserControl" />
</div>
<div>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />
<asp:Label ID="lblNAme" runat="server" Text="Label"></asp:Label>
</div>
</form>
Run and test the application.
Regards
Santosh Singh