Using Templates with ASP.NET Controls
page 1 of 1
Published: 02 Jun 2006
Unedited - Community Contributed
Abstract
This article will demonstrate how to work with Templates using ASP.NET 2.0
by Web Team at ORCS Web
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 8496/ 11

Using Templates with ASP.NET Controls

Something that is very useful when writing web pages that perform data inserts or updates is to restrict the options for certain fields to specific values.  One way to do this is to have the update options be items listed in a drop-down box.  Then the user can select one of the items from the list, and ONLY one of the items in the list, to set that value in the database.

I have written code to do this plenty of times in the past, but with ASP.NET 2.0 out now and the availability of tools like Visual Web Developer (VWD), I wanted to try this without writing ANY code.  I accomplished it, but it was not easy - mainly because I was tackling this without any direction.  I did a lot of fumbling around before I got the settings exactly right.  I will spare you the details of my mistakes and go right into how to do this properly, so it will be easy for you to do it yourself.

"Templates" are the term for how this is handled with ASP.NET.  I did not use Visual Studio with ASP.NET 1.x, but I think the "template" process with v2.0 is very similar to how it worked in v1.x. In this sample I will create a GridView.  Then I will adjust one of the columns to be a drop-down list that is actually populated with data from a different table.  The drop-down list should default to the value that matches the data and it should update the main table when the drop-down list is changed in edit mode.

For this sample I am using two tables in a Microsoft SQL Server database.

The first table is _Users and has four columns.
- UserID is an integer data type and is the primary key.
- Username is a 20 character text field.
- Password is a 20 character text field.
- TypeID is an integer data type.

The second table is _UserTypes and has two columns.
- TypeID which is an integer data type and is the primary key.
- TypeDescription is a 20 character text field.

Go ahead and populate the tables with some sample data so you can play around with it when the page is done.

I first cranked up VWD and created a blank WebForm page.  I also set up a data connection to the SQL Server that I am using in this sample.  I will not go through these steps because they are pretty simple and I am sure there is already good information online if needed.

I then expanded the data connection and the table's folder beneath it.  I dragged the _Users table from the data connections list onto my blank page.  This automatically creates a GridView and formats it by default to all of the columns in the table.  The GridView tasks box opens automatically - there I checked the box for "Enable Paging" and "Enable Editing."

Running the page right now will show the data from the _Users table.  This allows me to page through the results (if there are more than will display on a single page) and make updates to the data.  I want to limit the updates to the TypeID field though, so it has to match a value from the _UserTypes table.  That is the field I want to set to use a drop-down list.

Clicking on Edit Columns brings up a dialog box that will let me set some properties for each table column.  I selected TypeID in the "Selected Fields" box on the left to see the properties on the right.  Down below where all the properties are listed is a link that reads "Convert this field into a templatefield."  I clicked that link and then clicked "OK" to close that dialog box.

The GridView Tasks box should still be open from earlier.  I clicked on Edit Templates; this is where we will set up the TypeID template format.  From the Template Editing Mode box I selected the TypeID in the Display dialog.

Notice that there are five different templates that can be defined for this column.  The options are the following.

1.      ItemTemplate is how the data will look when it is displayed in a read-only format.

2.      AlternatingItemTemplate controls the look of the display if you wish to have alternating rows with a different appearance.

3.      EditItemTemplate is how the column is handled in edit mode; this is what we want to control.

4.      InsertItemTemplate controls how the insert of a new row is handled.  This can also be a nested control similar to how we are going to configure the EditItemTemplate.

5.      HeaderTemplate controls the look of the header for that column value.

The EditItemTemplate has a TextBox control in there by default.  I clicked the TextBox control and deleted it from the screen.  Then I dragged a DropDownList control from the Toolbox into the area where the TextBox was just removed.

Then I configured the data source for this control by clicking the Choose Data Source button.  This opens the dialog pages to configure the data source.  On the first screen I selected New DataSource.  On the next screen I chose Database, since the data will be pulled from a table.  On the next screen I chose my database connection string (there should be one in the drop-down list already) and clicked "Next."  On the next screen I selected the _UserTypes table, since that is where the drop-down will be populated from.  When it lists the available columns, I selected both TypeID and TypeDescription.  Clicking "Next" and then "Finish" completed those configuration items.  This now opens the Choose a Data Source option box.  I left the data source as the one that was just configured and selected TypeDescription in the display box and TypeID in the value box.  That will show the descriptions as the options, but pass the value back to the database on updates.  I clicked "OK" to finish.

If you were to run the page right now, it would appear that it is working as desired.  However, when an option is selected in the drop-down for type and the "update" is clicked to save the data, the option selected is not saved (it actually saves Null to that column in the table).

Here is how I got past this issue.  I opened the DropDownList Tasks box and clicked on Edit Databindings.  On the dialog box that opened, I highlighted Selected Value on the left-hand side of the box and then choose TypeID in the "Bound to" field on the right-hand side of the box.  The "Two-way databinding" option should already have a checkmark next to it (check it if it does not). Then I clicked "OK" to finish.

Run the page now and you will see that it works exactly as desired!  It may seem like a lot of work, but once you know how to do it, it is much faster than hand-writing the code to handle this manually.

Happy Coding!



User Comments

Title: lol   
Name: funny.
Date: 2010-06-14 11:43:49 AM
Comment:
here is the same procedure on msdn:
http://msdn.microsoft.com/en-us/library/ms178294.aspx
#Displaying a Drop-Down List While Editing in the GridView Control
Title: Error   
Name: Bob
Date: 2009-10-21 7:34:34 AM
Comment:
'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value

This error happens because you have DataTextField and DataValueField of the combo the wrong way around. i.e when databinding the combo make sure you have:

Data field to display = TypeDescription
Data field for the value = TypeID

and not the other way around.
Title: Error   
Name: Penny
Date: 2009-02-04 6:18:14 PM
Comment:
'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value

I'm also getting this error. The value DOES exist in the data source. Is it because my field is an int? DropDownList1.SelectedValue will return a string. But I don't know how to do a "convert" in the data binding? Can anyone help with this?
Title: Field Bindings grayed out...   
Name: Mike
Date: 2008-02-27 3:31:00 PM
Comment:
I am having a similar problem like coleen. I can't bind using Field Bindings. It is always grayed out.
I have to use the custom binding button and manually enter the binding statement.

Is this a Visual Studio bug. I have the latest VS 2005 service pack installed.
Title: could be better   
Name: Catalin
Date: 2008-02-03 8:10:04 AM
Comment:
some print screens would be nice, but this article is enough explanatory, for me just works.
Title: Field Bindings grayed out...   
Name: Coleen
Date: 2007-12-31 6:00:33 PM
Comment:
The article would be lots better with screen shots, but I did find out 1 thing that may be relevant to my problem of not getting the value from my datasource to display in the dropdownlist - it displays the first item in the list - which may not be the itme in the data. So on your instructions you have a section about the "Bound To" Field. Unfortunately, my Field Bindings are grayed out! I can't select Bound to. Any idea why this would be? thanks :-)
Title: Not Good   
Name: Raj Kumar
Date: 2007-10-09 3:50:28 AM
Comment:
The contents you provide is not sufficienct for a begineer programmer so enchance your material.
Title: Item Template   
Name: J.Brazinski
Date: 2007-08-10 2:48:18 PM
Comment:
I solved the invalid value problem by adding a blank line to the table that is the source of the dropdown. But I still don't get updates. No errors, but no updates. My field is bound and the checkbox is checked.
Sometimes, when I switch between edit & view modes I get this error:
Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.
I have no idea what it means. Can anyone help?
Title: asp.net d   
Name: Ravichandran
Date: 2007-02-11 2:36:07 PM
Comment:
'ddlbtitle' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value
Title: ItemTemplate   
Name: Tim
Date: 2007-02-09 2:49:35 PM
Comment:
How do you make the ItemTemplate view show the "display" data rather than the key?
Title: Fix for SelectedValue Invalid   
Name: Michael H
Date: 2006-11-14 10:05:37 AM
Comment:
'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value

This is caused because the dropdown list does not contain a value equal to the current value in the databound row. To fix this:
1. You can add a row to the user_type table that is the same as the default value of the column in the users table.
2. You can create an itemlist with a value that matches the default value of column in the users table and then use the AppendDataBoundItems="true" as a dropdown list property.
Title: SelectedValue which is invalid   
Name: Brad
Date: 2006-11-02 8:05:41 AM
Comment:
Please be sure to do the article steps exactly because trying to customize it for you own use. I've gone through it a couple of times without problems, as have a couple of readers, so it seems a small step is getting missed by some people.

~bk
Title: Null update error   
Name: Brad Kingsley
Date: 2006-11-02 8:03:08 AM
Comment:
If you are getting a Null update error - please note these paragraphs:

"If you were to run the page right now, it would appear that it is working as desired. However, when an option is selected in the drop-down for type and the "update" is clicked to save the data, the option selected is not saved (it actually saves Null to that column in the table).

Here is how I got past this issue. I opened the DropDownList Tasks box and clicked on Edit Databindings. On the dialog box that opened, I highlighted Selected Value on the left-hand side of the box and then choose TypeID in the "Bound to" field on the right-hand side of the box. The "Two-way databinding" option should already have a checkmark next to it (check it if it does not). Then I clicked "OK" to finish. "

~bk
Title: Mr   
Name: Andy Daniels
Date: 2006-11-02 7:20:27 AM
Comment:
I too get the below error...and cant hind a solution on the net...can anyone help?

'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value
Title: Doesnt work   
Name: Dave
Date: 2006-07-14 12:30:25 PM
Comment:
'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value

I have been searching arround on the internet about this, and it seems that some people get this to work just as intended and others get the error I am getting. I dont understand what setting must be different that we are not catching?
Title: fails to update   
Name: xxx
Date: 2006-06-13 6:59:48 PM
Comment:
the update fails complaining that it can't store Null in the Type field... thus the Type has not been assigned from the templated dropdown
Title: Nice Try but...   
Name: CD
Date: 2006-06-13 6:52:34 PM
Comment:
IT didn't work... when you get to the Databindings in the second the last paragraph... the _Users table fields are showing NOT the _UserTypes...

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-20 9:06:19 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search