Create your own User Control in ASP.NET

As a matter of fact, the build in Web Server controls in ASP.NET, allow you to create very good looking and functional Web pages without any effort. There are several built in data sources which you can use and access databases with just a few clicks,  some buttons, textboxes, image controls, update panels, data pager and so on. You can just drop them in you Web Pages, maybe double click them and configure the way you want to work. When you use these controls, you usually add in your page something like that: “asp:NameOfControl”, for example to add a web server button control you write:

<asp:button id="SendButton" runat="server"> 

Though, sometimes you need to create your own user controls. Take for example that you run your own company and this company has many offices around the world. In your company’s central website, you would like to have a page, to allow users contact with your offices. That page has just some links that sends the user to the respective office’s contact page. But all offices contact pages are actually the same. They contain just a form that the user must fill in with his details and a button to send his message. The form contains simple textboxes and a button. Instead of writing the same code over and over again to all these pages, you could just create a User Control, and just use it as if it was a build in Web Server control. Let’s see it in action now.

Create a new empty ASP.NET website in Visual Studio and add a new folder called “Controls”. Also add a new Web Form to your site. This page will be our Contact page.Right click the controls folder and add a new Item. Select a “User Web Control” and name it “ContactUserControl.ascx”. Make sure the “Place code in separate file” checkbox is checked. Your solution should look like this right now.

usercontrol1

Open the “ContactUserControl.ascx” file in source mode and paste the following code.

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="ContactUserControl.ascx.cs" Inherits="Controls_ContactUserControl" %>
<style type="text/css">
    .ErrorMessage {
        color: red;
    }
</style>
<table class="auto-style1" runat="server" id="FormTable">
    <tr>
        <td colspan="3">
            <h1>Contact our office</h1>
            <p>
                Enter your name, e-mail address, and your home or business phone number to get in touch with us.
            </p>
        </td>
    </tr>
    <tr>
        <td>Name</td>
        <td>
            <asp:TextBox ID="Name" runat="server"></asp:TextBox>
        </td>
        <td>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="Name" CssClass="ErrorMessage" ErrorMessage="Enter your name">*</asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td>E-mail address</td>
        <td>
            <asp:TextBox ID="EmailAddress" runat="server" TextMode="Email"></asp:TextBox>
        </td>
        <td>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="EmailAddress" CssClass="ErrorMessage" Display="Dynamic" ErrorMessage="Enter an e-mail address">*</asp:RequiredFieldValidator>
            <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="EmailAddress" CssClass="ErrorMessage" Display="Dynamic" ErrorMessage="Enter a valid e-mail address" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator>
        </td>
    </tr>
    <tr>
        <td>Repeat e-mail address</td>
        <td>
            <asp:TextBox ID="ConfirmEmailAddress" runat="server" TextMode="Email"></asp:TextBox>
        </td>
        <td>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="ConfirmEmailAddress" CssClass="ErrorMessage" Display="Dynamic" ErrorMessage="Confirm the e-mail address">*</asp:RequiredFieldValidator>
            <asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="EmailAddress" ControlToValidate="ConfirmEmailAddress" CssClass="ErrorMessage" Display="Dynamic" ErrorMessage="The e-mail addresses don’t match">*</asp:CompareValidator>
        </td>
    </tr>
    <tr>
        <td>Home phone number</td>
        <td>
            <asp:TextBox ID="PhoneHome" runat="server"></asp:TextBox>
        </td>
        <td>
            <asp:CustomValidator ID="CustomValidator1" runat="server" ClientValidationFunction="validatePhoneNumbers" CssClass="ErrorMessage" Display="Dynamic" ErrorMessage="Enter your home or business phone number" OnServerValidate="CustomValidator1_ServerValidate">*</asp:CustomValidator>
        </td>
    </tr>
    <tr>
        <td>Business phone number</td>
        <td>
            <asp:TextBox ID="PhoneBusiness" runat="server"></asp:TextBox>
        </td>
        <td>&nbsp;</td>
    </tr>
    <tr>
        <td>Comments</td>
        <td>
            <asp:TextBox ID="Comments" runat="server" Height="63px" TextMode="MultiLine" Width="308px"></asp:TextBox>
        </td>
        <td>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="Comments" CssClass="ErrorMessage" Display="Dynamic" ErrorMessage="Enter a comment">*</asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td>&nbsp;</td>
        <td>
            <asp:Button ID="SendButton" runat="server" Text="Send" OnClick="SendButton_Click" />
        </td>
        <td>&nbsp;</td>
    </tr>
    <tr>
        <td colspan="3">
            <asp:ValidationSummary ID="ValidationSummary1" runat="server" CssClass="ErrorMessage" HeaderText="Please correct the following errors:" />
        </td>
    </tr>
</table>
<br />
<asp:Label ID="lblMessageSent" Text="Thank you for your message. We'll get in touch with you if necessary."
    runat="server" Visible="false" CssClass="ErrorMessage"></asp:Label>

Switch to design view and see how your contact form looks.

usercontrol2

If you take a look at the source code you ‘ll notice that I have just added some textboxes and some build in validation controls. This is not a validation tutorial so I assume you have an idea about how they work. Maybe we look how these work in another post. Don’t worry about that, we just want to see how to use that control now in our pages. Before use the control in our Default.aspx page switch to the Code behind file of the user control and paste the following code. This code simple handles the “Click” button’s event and checks if Phone numbers are valid.

public partial class Controls_ContactUserControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (!string.IsNullOrEmpty(PhoneHome.Text) || !string.IsNullOrEmpty(PhoneBusiness.Text))
        {
            args.IsValid = true;
        }
        else
        {
            args.IsValid = false;
        }
    }
    protected void SendButton_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            lblMessageSent.Visible = true;
        }
        else
            lblMessageSent.Visible = false;
    }
}

Go straight to your Default.aspx page and under the Page directive add a new Register directive like this.

<%@ Register Src="~/Controls/ContactUserControl.ascx" TagPrefix="UserControl" TagName="ContactUserControl" %>

What this does, is to register into that page our user control that resides under the “Controls” folder. Also, tells the page, that in order to use that control, simply add a “UserControl” prefix followed by the name “ContactUserControl”. Go now and add this user control inside the only div in your Default.aspx page.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Src="~/Controls/ContactUserControl.ascx" TagPrefix="UserControl" TagName="ContactUserControl" %>
<!DOCTYPE html>

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

Built the website and run the Default.aspx page. Unfortunately you ‘ll get an error.

usercontrol3

This has to do something with Client and Server validation. Just add the following line in your Web.config file and try to run the page again.

<?xml version="1.0"?>

<configuration>
  <appSettings>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
  </appSettings>
    <system.web>
      <compilation debug="false" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
    </system.web>

</configuration>

usercontrol4

Leave some values empty and see how validation works. Then fill all the fields with valid values and press the button. Your user control works just fine!

usercontrol5

Most times, you will probably want to use your user controls in many pages, so instead of adding a “Register” directive in every page as we did in the Default.aspx, just register the control in your Web.config file and it will be accessible in all of your pages.

<?xml version="1.0"?>

<configuration>
  <appSettings>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
  </appSettings>
    <system.web>
      <compilation debug="false" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
      <pages>
        <controls>
          <add src="~/Controls/ContactUserControl.ascx" tagPrefix="UserControl" tagName="ContactUserControl"/>
        </controls>
      </pages>
    </system.web>

</configuration>

Remove the “Register” directive from your Default.aspx page and see that it still works.

Advertisements


Categories: ASP.NET

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Diary Of A Programmer

Because every day is worth noting

Chara Plessa

The purpose of this blog is to broaden my education, promote experimentation and enhance my professional development. Albert Einstein once said that “If you can’t explain it simply, you don’t understand it well enough” and I strongly believe him!

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Kumikoro

A Front End Developer's Blog

Muhammad Hassan

Full Stack Developer | ASP.NET | MVC | WebAPI | Advanced Javascript | AngularJS | Angular2 | C# | ES6 | SQL | TypeScript | HTML5 | NodeJS, MS candidate @LUMS, Grad & EX-Adjunct Faculty @NUCES-FAST, seasonal blogger & open-source contributor. Seattle, WA.

Software Engineering

Web development

IEvangelist

.NET, ASP.NET, C#, MVC, TypeScript, AngularJS

leastprivilege.com

Dominick Baier on Identity & Access Control

Happy DotNetting

In Love with Technology

Knoldus

Knols of experience to your advantage

knowshnet

Search - Read - Request - Share

Rahul's space

Learn, Share and Grow with me !

Dhananjay Kumar

Developer Evangelist @Infragistics | MVP @Microsoft |

SQL Authority with Pinal Dave

SQL Server Performance Tuning Expert

Conficient Blog

Random bits of tech from @conficient

Code! Code! Code!

SOLID & KISS

Code Wala

Designing and coding

Microsoft Mentalist

A way to start with Microsoft Technologies

Tony Sneed's Blog

A glimpse into the lives of Tony & Zuzana Sneed

%d bloggers like this: