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" "">
<html xmlns="">
<head runat="server">
<form id="form1" runat="server">
<div id="specialdiv" class="previewWrapper">
<uc1:PreviewCS ID="previewControl" runat="server"></uc1:PreviewCS>
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 × +