Watch videos with subtitles in your language, upload your videos, create your own subtitles! Click here to learn more on "how to Dotsub"

[How Do I:] Create a Custom User Control in ASP.NET?

0 (0 Likes / 0 Dislikes)
  • Embed Video

  • Embed normal player Copy to Clipboard
  • Embed a smaller player Copy to Clipboard
  • Advanced Embedding Options
  • Embed Video With Transcription

  • Embed with transcription beside video Copy to Clipboard
  • Embed with transcription below video Copy to Clipboard
  • Embed transcript

  • Embed transcript in:
    Copy to Clipboard
  • Invite a user to Dotsub
Hi. My name's Chris Pels. In this video we're going to learn how to build a custom user control in ASP.NET. To get started let's add a new website to our empty solution. We'll just create a regular ASP.NET website, and we'll call it website VB. So our objective it to build a custom user control that we can use anywhere in the website just like we can use a text box or a button control that comes with ASP.NET. Now what I like to do, which is by no means required, is to create a folder called controls, and I put my user controls in that folder. I should say I put user controls in this folder that are potentially used in various places across my website. They're kind of general user controls. Then another practice that I do is let's say I have a folder called events. This events folder contains web pages that relate to event-based functionality. If I have user controls that are specific to those event pages, what I do is create a child folder called controls, and I put the user controls in that folder. The reason for doing this is 1) It provides a nice organization so that the user controls related to events are contained within the events folder, and it also provides the flexibility to secure this controls folder should I need to do so. So to get started building our user control what we need to do is add a new item to our controls folder, and it needs to be a web user control template item. We're going to call this address because what we're going to do is to build an address-based user control that we can use throughout our website. Now this creates an ASCX file, very similar to the ASPX file. You'll see there's no body or form tag in here, but we do add any kind of HTML to the user control that we would add to a webpage. You also see that it has a control tag indicating it is a user control. It has the language specified much like a page as well as there's a code file behind the user control in the same way that we have one for a webpage. So let's get started designing our user control. I'm going to start by putting a DIV element which will be the kind of outer master container for all the HTML that we'll put in our user control. Just to demonstrate a principle I'm going to put the word address here. One of the things is that you can't use a user control as the start page. So in order to see the user control live on a webpage, you need to put it on a webpage. What I tend to do is to either create a temporary webpage where I put the user control, or I put it on one of the pages that it will be used on in the live site as I'm developing it so I can run that page and see what the control looks like and how it performs on a live site. So let's do that. Let me just save it. We're going to go over to default ASPX, and one easy way to put a user control on the page is to go into the design mode, and we're just going to take the address user control and drag and drop it on the page. You can see we're getting the address text that I put in my user control, and now we'll run this, and you'll see that we'll be able to view our user control even in its simple form here on a live webpage. So let's get started building our user control. What we want is to have a layout with a couple of lines for the user to enter their address: City, state, post code, and country. I'm going to use DIVs to do the formatting for our user control. The first thing I want is a label for address line 1. So I'm going to take a label, and we'll put that inside this DIV, and we'll add a second DIV. In that one we're going to put a text box where the user can enter the information for address line 1. Let me format this a little bit. I'm going to use classes to format our elements a little bit, just enough so we can have a nice readable format. This first one I'll call input element. Then the second one we are going to call input label. The third one we'll call input data. So this is for address line 1. Let's just use that as a basis for our other input elements. So we have address line 2—city, state, postal code, and country. Now let's just go back up and start to put in some of the IDs. Label address 1. Text will be address 1. Text box will be address 1 as well. Now I'm going to do the rest of them here. Next we'll do the city. The text box. We'll follow that up with state. Text box for state. Do postal code. Text box for postal code. Last one will be for country. The text box. Now, as I said, I'm going to control some of the formatting with some CSS styles. So let's go ahead and create a theme for our website. We're going to call it default. Inside the default theme we're going to add a new style sheet, and we're going to call this default screen. In here we need to put a few of the classes that we created. We had input element. We had input label. We had input data. For our input element, let's just put a little bit of a margin. We'll put 5 pixels on the top, zero on the right, 5 on the bottom, and zero on the left. Down to our label. Let's just put a little bit of padding. Let's put 2 pixels all the way around. Let's copy that, put the same thing for our input data. Let's go back up to our input element, and we'll clear both because we're going to use some floats here on our label. We want our label to float left, and we also want our data to float left. With our label we also want the text to align to the right. Before we go any further, let's make sure to remember to go over here to our web.config and specify the theme we can use, and that's default. We'll just save that. So let's check out how this looks, and one of the things you will find when creating a user control specifying a theme in the CSS is that even when we go in the design mode we're not seeing the exact layout, and that's another reason for dropping the user control over here in the page, so let's fire up default ASPX, take a look. We're getting reasonably close to what we want for our layout on the page. Now let's just specify a few properties of some of our text boxes because some will be longer than others, and we'll give 50 columns for address. The max length, let's say our database is 50 as well. We'll do the same thing for address 2. The max length. Our city. Let's make that 35 columns but potential max length for 50. The state. Let's make the state 2 columns. They have to use the abbreviation for what we're doing, and the max length is 2 now. Another alternative is we could put a drop-down list in here that is data-bound to a table in our database that lists all the states so we'd have a standardized list of states and then use a primary key to store the state value in our address. So that's something to consider. We're going to add the postal code, and let's make this 10 columns with a max length of 10. We're doing this just as a US-based address and country. Again let's make that 25 columns, but the max length we'll make 50. So let's just run the page and view it again to make sure we're getting what we want. Indeed now it's much closer to what we want. We probably would want to align these labels and text boxes as well. So the next thing we like in our user control is to have some standardized validation. The first validation that we would like is to have the city be a required field. We'll take a required field validator, and we'll put that out here to the right of the text box. We'll call that required validator city. The error message will be city is required. The text we're going to display in this case is the letter R. Now what we're going to do is give this a CSS class of validation message, and then we need to specify the control to validate, which in this case is TXT city. Let's just go over to the CSS and add our validation class. We'll add 2 things: One is the color. We'll say it's red. We want the font weight to be bold. We go back over to our user control, and if we check out our default ASPX we'll see that it is showing up red and bold as we wanted it. So now we're going to go back, and we're going to add a few more validation controls. Let's say we also want the state to be required. So I'm just going to copy and paste the one we used for city and use it with state; however, we need to make a few changes. We want to have it validate the state instead, and we'll call it required validator for state. We'll just change the message to state is required. Now we'll just do a few more validations. We're going to also put required down here for the postal code. Make the necessary changes. Change the name or the ID I should say. The control to validate is the postal code, and we'll just change the message. The last validation that we're going to use is to put a regular expression validator, and we'll put that on the postal code so we ensure that people enter it in the right format. We'll just call this regular expression validator postal code. We'll set the control to validate to be the postal code. We'll set the CSS class to validation message. The message will say postal code must be in the format. We'll put that error text as R. The expression—we're going to use one of the canned expressions that we have here in ASP.NET for the U.S. zip code. I'm actually going to go back to the text, and let's put something a little more informative. We'll say format must be— Now we could put more complex validation here if we wanted to, but the key point is that whatever validation we put here in our address user control will be applied consistently across the application or website, wherever the user control is placed. Let's just go back to our default page, and what I'd like to do is to get a button so we can post back and test out the validation. For the moment we'll just put the button here on the page. Let's do a quick test before we leave the validation. Fire up the webpage. We'll just click our button to submit. We do see that we get our validation error messages indicating those fields are required. Let's just put 3 digits rather than our required format in postal code, and we do get the format message; however, you saw that it's offset to the right. So what we need to do is to go back over to our address, and we need to make this display dynamic for the required R, and that means that it will shift over to the left or basically that the required validator doesn't take up any space unless it is invalid. Another thing that we might want to do with our user control is to be able to expose some properties that could be set by the container that's using the control, and let's say that we want to have an enabled property for our user control much like over here on the default page. If we look at the button, the button has an enable property. Now by default our user control will not have an enable property, so in order to add that what we need to do is to go down into the code behind, and we need to add a public property called enabled. To set it and get it, there's a couple of approaches, and what we'll do is we'll create a private variable called _enabled. That's Boolean. So we come in here to our enable property, and we'll say _enabled, or rather we'll return _enabled. Down here we'll set it. The other thing we'll need to do is to actually set the enabled property of our contained controls, in this case the text boxes, so we have address 1. Enabled equals the value passed in. Address 2 equals the value, and we have city, state, postal code, and country. So now when we go back over to default ASPX where the user control is located or used, we can set the enable property in 1 of 2 ways. If we go into the address tag for the user control, we'll see there's now an enable property, and we could set it here. Enabled equals true or false. We could also go into the code behind, and we could set the property programmatically here, let's say in the unload event. So we go to address 1 which is the ID of the user control on the default page, and there's enable property—we could set that to false. Now if we start up the webpage since we've set it to false you'll see that I cannot get access to any of our text boxes on the page. So let's just get rid of that because we don't want that around. So we could go back over here to our code behind, and we could add properties for other operations or settings that we want for our user control. One of the other issues that needs to be addressed in a user control like this is how do we set or get the values of the address elements inside our user control? There's 2 approaches to that, and one would be that we create a property for each of those. Let me go ahead and do that, let's say, for city so you can just see how that would work. A public property city as a string. I just noticed that we should have typed our enable property here, so we'll just do that. Go down here as—correct that for you so when you get the sample code you'll have the right code. So now what we want to do is we want to return the text from our text box, and we'll trim it. Then if we set it we want to do the opposite. Set it to the value past the property. So then we could create additional properties for the other fields such as the state, postal code, etc. Now while this approach of creating properties for each of the UI elements inside our user control does provide a lot of flexibility so that whatever is containing this user control could individually set properties, it also doesn't provide as much of a black box-type approach where the control knows how to load its data and how to save its data. It may need to perform intermediary validations or conversions of fields as it does so. So a second approach, and you can decide in the end which is best for you, you may use both, is to create 2 properties or I should say 2 methods: One that loads the data and one that saves the data. So let's create the first one. We'll call it load data. We'll have it take the data. Let's say a data table. As input as system.data.datatable. This returns a Boolean whether or not it was successful. Then we might actually do a second method. Public function called save data. This would also take a data table and return a Boolean. Then in each of these methods you would need to do what we did up here with the city property and in the case of save data. We would need to take our save the data to our data table and perform any validation. Same thing would be true with our load data is we would want to take the values from the data table and put them into the UI elements. We wouldn't want to forget to return either true or false depending upon the success of loading or saving our information. One point to make here just to be clear that we're not loading and saving the data to the database in these 2 methods but simply transferring it from the user interface elements to some sort of storage structure that would then be returned, and it would be saved to the database as another part of the application. Now here in our example I specified a data table as the container in which we get data in and save data. Another alternative would be if you have created an address class so that you have an address object. You could pass in the address object and load the data from it or save the data back into it. Looking forward with .NET framework 3.5 when we have the entity classes, if you have an address entity then you might pass that in, and you could use some of the new features like the link data source to bind it to the user interface elements. The right approach is really up to your situation and what you feel might work best for your team. Now one last thing I'd like to do is maybe somewhat obvious, but I want to do it regardless just so everyone's clear on this. I'm going to add a new page to the events folder called default ASPX, and then we're going to open that page up in the design mode, and we're going to go over to our address user control. We're going to drag and drop it onto this page. You can see we have all of the functionality of our address user control here on the default page in the events folder which is identical to what we have in the default ASPX in the root of the website. This is an extremely powerful and useful approach to groups of user interface elements that are common across your website. In fact, almost any time you have the same group of elements used in 2 or more places, it may be worthwhile to consider creating a user control because then not only is the look of the control standardized, but all of the functionality such as saving and loading the data into the user interface elements as well as the validation is similar. If you externalize the formatting of the user control to a group of standard style class names then you have a lot of flexibility in controlling the look of your user control from one place to the next. So I encourage you to download the sample code, take a look at it in a little more detail, and think about how you can use it as a basis for creating user controls for use in your websites. This is Chris Pels. Thanks for watching this video on how to create a custom user control in ASP.NET.

Video Details

Duration: 27 minutes and 41 seconds
Country: United States
Language: English
License: All rights reserved
Genre: None
Views: 5
Posted by: neudesicasp on Aug 26, 2013

In this video Chris Pels will demonstrate how to create a custom user control in ASP.NET that can be used throughout a web site or across many web sites. Start out by learning the basics of creating a user control that will be used in multiple pages including validation, controlling formatting using style elements, and loading/saving data for the user interface elements. Throughout the video considerations for building user controls that can be easily maintained and used across multiple pages are discussed.

Caption and Translate

    Sign In/Register for Dotsub to translate this video.