hi,
I want to know how can we use web user control through code behind file?
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
SenthilkumarPosted Apr 3, 2012, 11:42 PM
Web user control is important in asp.net and it reduces the redundancy code in our web page. It is used to implement the common functionality of the web page in across the sites.
It has the extension of (.ascx) and the control can be add in the Add New Item >> Web User Control.
The user control has to be registered in the web page or master page using the register directives. The register directives has the path of the control and it will generate the tagname and prefix to refer in the web page.
<%@ Register src="Concepts/WebUserControl.ascx" tagname="WebUserControl" tagprefix="uc1" %>
The register control needs to be refer in the required place of the web page.
Satyapriya NayakPosted Apr 3, 2012, 10:06 PM
Accessing user controls from the code-behind
When you add a user control to an ASP.NET page, Visual Studio .NET does not add a control declaration as it does when you add standard ASP.NET web controls. The result is that you can't directly access the user control from the code-behind and programmatically change its properties and call its methods. Well, you can, but you first have to declare the user control variable by hand, and then set it to the user control instance created on the page. Here's the code:
' declare the control
Protected MyCtl As MyUserControl
Private Sub Page_Init(sender As Object, e As EventArgs) Handles MyBase.Init
InitializeComponent()
' get a reference to the MyUserControl user control.
MyCtl = DirectCast(FindControl("MyCtl"), MyUserControl)
End Sub
From now on you can access the control and do something like:
MyCtl.BackColor = Color.Yellow
MyCtl.DoSomething()
If you program with C#, you still need to manually declare the control variable, but you don't need to explicitly set it to the control instance declared on the ASPX page. This is done automatically by the ASP.NET runtime, provided that the name of the control variable matches the name used for the control instance on the page.
Please refer the below links
http://msdn.microsoft.com/en-us/library/aa719972%28v=vs.71%29.aspx
http://www.devx.com/vb2themax/Tip/18843
http://asp.net-tutorials.com/user-controls/using/
Thanks