Live Chat Icon For mobile
Live Chat Icon

ASP.NET FAQ - User Controls

Find answers for the most frequently asked questions
Expand All Collapse All

In the .ascx:


<asp:Image id='Image1' runat='server'></asp:Image>

In .aspx

VB.NET


<uc1:UCImage id='UCImage1' source='b2346.jpg' runat='server'></uc1:UCImage>

Dim UC As UserControl
Dim imgUC As System.Web.UI.WebControls.Image
UC = Page.FindControl('UCImage1')
imgUC = UC.FindControl('Image1')
imgUC.ImageUrl = 'b2346.jpg'

C#


UserControl UC ; 
System.Web.UI.WebControls.Image imgUC ; 
UC = (UserControl)Page.FindControl('UCImage1');
imgUC =(System.Web.UI.WebControls.Image)UC.FindControl('Image1');
imgUC.ImageUrl = 'b2346.jpg';
Permalink

Here is an example of adding one UserControl into another:


uc1.ascx: 
<asp:Label runat='server' text='uc1' ID='Label1' />
<asp:Panel runat='server' id='p1' >Panel UC1</asp:Panel> 

uc2.ascx: 
<br><asp:Label runat='server' text='uc2' ID='Label1' />

VB.NET


Dim uc1 As UserControl = CType(LoadControl('uc1.ascx'), UserControl)
Controls.Add(uc1)
Dim uc2 As Control = uc1.LoadControl('uc2.ascx')
Dim p1 As Control = uc1.FindControl('p1')
p1.Controls.Add(uc2)

C#


UserControl uc1    = (UserControl)LoadControl('uc1.ascx');
Controls.Add(uc1);
Control uc2    = uc1.LoadControl('uc2.ascx');
Control p1    = uc1.FindControl('p1');
p1.Controls.Add(uc2);
Permalink

Create a User Control
Below Code goes in User Control


<asp:ImageButton id='ImageButton1' runat='server'></asp:ImageButton>

Create a property called source
VB.NET


Public Property source() As String
	Get
		Return ImageButton1.ImageUrl
	End Get
	Set(ByVal Value As String)
		ImageButton1.ImageUrl = Value
	End Set
End Property

C#


public string source 
{
	get 
	{
		return ImageButton1.ImageUrl;
	}
	set 
	{
		ImageButton1.ImageUrl = value;
	}
}

Now in your webform:
Drag and drop User Control and set the source property.


<uc1:UCImageButton source='b2346.jpg' id='UCImageButton1' runat='server'></uc1:UCImageButton>
Permalink

Create a User Control


<P>
<asp:Button id='Button1' runat='server' Text='Button'></asp:Button></P>
<P>
<asp:Label id='Label1' runat='server'></asp:Label></P>

On button Click
VB.NET


Label1.Text = 'Hello' 

C#


Label1.Text = 'Hello' ;

Create a Webform to use a UserControl


<asp:Panel id='Panel1' runat='server'></asp:Panel>

VB.NET


Dim myControl As Control = CType(Page.LoadControl('UC1.ascx'), Control)
Panel1.Controls.Add(myControl)

C#


Control myControl   =(Control)Page.LoadControl('UC1.ascx');
Panel1.Controls.Add(myControl);
Permalink

Share with

Couldn't find the FAQs you're looking for?

Please submit your question and answer.