<

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x

ASP.NET Web Form User Control's Basic Interaction

Published on
3,582 Points
582 Views
Last Modified:
Ryan Chong
(NIV) Hebrews 10:35 So do not throw away your confidence; it will be richly rewarded.
An ASP.NET Web Form User Control is not newly introduced in ASP.NET. In fact, it was an old technology yet still playing a role to generate web content, especially when we want to use it to have a better and easy way to control part of the web content that is being generated.

I saw a recent question regarding .NET - Render User Control Logo on Postback and decided to write an article to address the issue stated in that question. To add further, I would like to include some features to make this article a worthwhile read.


In general, I would like to discuss the following items:

  1. Create a simple Web Forms User Control
  2. Load a Web Forms User Control to an ASP.NET page
  3. What if I want to get the Web Forms User Control's selection from Parent's Page?
  4. What if I want to change the Web Forms User Control's selection from Parent's Page?
  5. What if I want the changes in Web Forms User Control to reflect in the Parent's Page?
  6. And finally, what if I want the changes in Web Forms User Control to reflect in the Parent's Page, this time by passing a dynamic control instead of hard-coded in codes?


I'm using Microsoft Visual Studio Community 2015 for illustration.


1. Create a simple Web Forms User Control


First of all, start a new project. In this case, I will use VB.NET for illustration purposes, since VB.NET was required in the question.



I'm selecting an Empty template and selecting Web Forms for Add folders and core references



Now go to menu Project > Add New Item... (or press Ctrl + Shift + A) to add a new item to your project.


First, we can add a Web Form from option, name it WebForm1.aspx



Second, we do the same but this time we try to add a Web Forms User Control from the option, named it as WebUserControl1.aspx



Now we can double-click the file item generated in the Solution Explorer to edit the codes.



First, let's try to edit the Web Forms User Control.


Once the item has been opened, you will see codes such as shown below:


<%@ Control Language="vb" AutoEventWireup="false" CodeBehind="WebUserControl1.ascx.vb" Inherits="VB2015_WebApplication1.WebUserControl1" %>


For an explanation of the above codes, you can refer to: @ Control


Now go to the Designer view (press Shift + F7), and you should see an empty "page" is displayed. Now we try to generate some contents by:


  • Typing some wordings directly on the page
  • Go to Toolbox (menu View > Toolbox) and add some controls, such as:
        a Label control (named as Label1)
        an Image control (named as Image1)
        a DropDownList control (named as DropDownList1)


When it's necessary, we can either set these controls with default Properties directly via the Properties window, or via Code Behind by writing the relevant codes.


We can switch the page back to Source view (press Shift + F7 again) to view the codes that were added, which could be like something below:


<%@ Control Language="vb" AutoEventWireup="false" CodeBehind="WebUserControl1.ascx.vb" Inherits="VB2015_WebApplication1.WebUserControl1" %>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<p>
    <asp:Image ID="Image1" runat="server" />
</p>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
    <asp:ListItem Value=""></asp:ListItem>
    <asp:ListItem Value="logo1.png">Logo 1</asp:ListItem>
    <asp:ListItem Value="logo2.png">Logo 2</asp:ListItem>
    <asp:ListItem Value="logo3.png">Logo 3</asp:ListItem>
</asp:DropDownList>


Now, my intention is to display a proper image (logo) based on the dropdown list selection. I can do that by selecting the DropDownList control and go to Properties, go to the Events icon and double-click the SelectedIndexChanged event.


Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownList1.SelectedIndexChanged
        If DropDownList1.SelectedValue <> "" Then
            Image1.ImageUrl = "./images/" + DropDownList1.SelectedValue
            Label1.Text = "You have selected: " + DropDownList1.SelectedValue
        Else
            Image1.ImageUrl = ""
            Label1.Text = ""
        End If
    End Sub


The above code means:

If the selected item in the drop-down list is not empty (user had selected Logo 1, Logo 2, etc) the code will try to look to the physical image file (like: logo1.jpg, logo2.jpg, etc) at folder: <root>/images. Label1 is used to display what user had selected.

We can do this by manually adding a folder named as "images" and put in the logo files.



Note:
Remember to add set the AutoPostBack property to True for the DropDownList control so that it will postback after the selection was changed.


Now, we are almost there so we try to include this Web Forms User Control into a normal ASP.NET web page.


2. Load a Web Forms User Control to an ASP.NET page


After we saved the changes on Web Forms User Control, we open up the Web Page (WebForm1.aspx) regardless of its Design, Source or Split view. And then select the Web Forms User Control (WebUserControl1.ascx) from the Solution Explorer and drag it to the Web Page.


By doing this, you should able to see that some additional codes were added:


<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="WebForm1.aspx.vb" Inherits="VB2015_WebApplication1.WebForm1" %>

<%@ Register Src="~/WebUserControl1.ascx" TagPrefix="uc1" TagName="WebUserControl1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <uc1:WebUserControl1 runat="server" id="WebUserControl1" />
    </div>
    </form>
</body>
</html>


So now save the Web Page and build your solution to see what you get!



The image logo and label's text should also be changed once the drop-down selection is changed.


Simple enough so we try to explore more.


3. What if I want to get the Web Forms User Control's selection from Parent's Page?


This is simple, we can use this code to achieve that:


Dim dropdown As DropDownList = TryCast(WebUserControl1.FindControl("DropDownList1"), DropDownList)
        If dropdown IsNot Nothing Then
            If dropdown.SelectedValue = "" Then
                Response.Write("You have selected nothing")
            Else
                Response.Write("You have selected logo: " + dropdown.SelectedValue)
            End If
        End If


4. What if I want to change the Web Forms User Control's selection from Parent's Page?


You can try:


'Select the 2nd item in the DropDownList control
        Dim dropdown As DropDownList = TryCast(WebUserControl1.FindControl("DropDownList1"), DropDownList)
        If dropdown IsNot Nothing Then
            dropdown.ClearSelection()
            dropdown.SelectedIndex = 2
        End If


or use:


Dim dropdown As DropDownList = TryCast(WebUserControl1.FindControl("DropDownList1"), DropDownList)
        Dim itm As ListItem = TryCast(dropdown.Items.FindByText("Logo 1"), ListItem) 'Select the 2nd item in the DropDownList control
        If itm IsNot Nothing Then
            itm.Selected = True
        End If


5. What if I want the changes in Web Forms User Control reflect in the Parent's Page?


Let's say we want to display the text of Label Control in Web Forms User Control into the Parent's Page's Label Control:


Assume we have a Label Control in Parent's Page named as ParentLabel:


<asp:Label ID="ParentLabel" runat="server" Text="Label"></asp:Label>


Then for the Web Form User Control, we can apply the following codes:


Dim ParentLabel As Label = TryCast(Me.Parent.FindControl("ParentLabel"), Label)
        If ParentLabel IsNot Nothing Then
            ParentLabel.Text = Label1.Text
        End If


6. Finally, what if I want the changes in Web Forms User Control to reflect in the Parent's Page, this time by passing a dynamic control instead of hard-coded in codes?


So, what if it's the nature that we only know what Label object we're going to use in a later period, along with the fact that not everytime we get a control named as "ParentLabel", I wish to dynamically set the reference to that control?


In that case, we can make the following changes to address the issue.


First, create a Public Object (in this case, we use a Label control) in Web Forms User Control's code behind:


Public ParentLabel As Label


And then remove this line from existing codes:


Dim ParentLabel As Label = TryCast(Me.Parent.FindControl("ParentLabel"), Label)


If we now re-build the solution, it seems that no error will occur but at the same time, nothing will be reflected in Parent's Page. Reason being the ParentLabel is now declared publicly and not yet been assigned.


To make this work, in the Page_Load event of Parent's Page, we need to assign the Label control accordingly (let's say this time we would like to reflect the value into another Label control named as ParentLabel2.


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        WebUserControl1.ParentLabel = ParentLabel2
    End Sub


Finally, we re-build the solution. It seems everything is working fine now in which ParentLabel2 has displayed the text of Label1 in Web Form User Form.



Summary:


The illustration above is just to share a bit of my personal experience with using Web Form User Control in ASP.NET development. In real scenarios, it can get much more complex and in a bigger context in which more logical validations or interfaces need to be integrated together, but for now, this article should be a good enough starter for beginners.


Please don't hesitate to provide your comments and I shall update this article in due course.


Cheers!


0
Comment
Author:Ryan Chong
0 Comments

Featured Post

CompTIA Network+

Prepare for the CompTIA Network+ exam by learning how to troubleshoot, configure, and manage both wired and wireless networks.

Join & Write a Comment

This tutorial demonstrates how to identify and create boundary or building outlines in Google Maps. In this example, I outline the boundaries of an enclosed skatepark within a community park.  Login to your Google Account, then  Google for "Google M…
This tutorial walks through the best practices in adding a local business to Google Maps including how to properly search for duplicates, marker placement, and inputing business details. Login to your Google Account, then search for "Google Mapmaker…

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month