Thursday, February 14, 2013

How to Find Controls inside a UserControl in ASP.NET


Assume that you have a simple user control which contains a button control.

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="PreviewCS.ascx.cs" Inherits="PreviewCS" %>
<asp:Button ID="btnPrint" runat="server" Text="Print" />
Using the below code we can add the UserControl to our main web page.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Wizard.aspx.cs" Inherits="Wizard" %>
<%@ Register Src="PreviewCS.ascx" TagName="PreviewCS" TagPrefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div id="specialdiv" class="previewWrapper">
<uc1:PreviewCS ID="previewControl" runat="server"></uc1:PreviewCS>
</div>
</form>
</body>
</html>
To find the button control inside the user control from the main page code behind use the below code.
private void FindButton()
{
Control previewControl = this.NamingContainer.FindControl("previewControl");
Button printButton = (Button)previewControl.FindControl("btnPrint"); }

No comments:
Write comments
Recommended Posts × +