Wednesday, May 5, 2010

How to access control from another user control in Asp.Net page

Hi ,
Create new website and add two .ascx pages .
Write coding for both user control and drag that user controls on default page.

Enter Below Code into ControlA.ascx page in source mode::

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="ControlA.ascx.cs" Inherits="ControlA" %>





Enter Below Code into ControlA.ascx.cs file
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class ControlA : System.Web.UI.UserControl
{
string settext;
public string text
{
//get
//{
// return TextBox1.Text;
//}
set
{
TextBox1.Text = value;
}
}

protected void Page_Load(object sender, EventArgs e)
{

}
}

Create second User Control add button control to it::

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="ControlB.ascx.cs" Inherits="ControlB" %>
<%@ Reference VirtualPath="~/ControlA.ascx" %>





After Click on Button call page.findcontrol method & get respected output::


public partial class ControlB : System.Web.UI.UserControl

{
protected void Page_Load(object sender, EventArgs e) {
}
protected void Button1_Click(object sender, EventArgs e) {
ControlA FirstUserControl = (ControlA)Page.FindControl("ControlA1");
FirstUserControl.text = "Hi";
}}

And The two control are communicating with each other

1 comment: