Working with DropDownLists in DataGrids
page 1 of 1
Published: 04 Nov 2003
Unedited - Community Contributed
Abstract
DropDownLists are very useful controls which can be used to accept input from users. This control can be better used if we know the range for the input. The user feels more comfortable with DropDownLists (combo boxes) rather than textbox, since the keyboard should be used to provide input to the latter. In this article, we will see how can we use a dropdownlist inside a datagrid.
by Jesudas Chinnathampi (Das)
Feedback
Average Rating: 
Views (Total / Last 10 Days): 25113/ 39

DataGrid and DropDownLists:
How DropDownlists works in edit mode and how to preset an item in a dropdownlist in edit mode.

Written on: July, 18th 2002.
Introduction

DropDownLists are very useful controls which can be used to accept input from users. This control can be better used if we know the range for the input. Users feel more comfortable with DropDownLists (combo boxes) rather than textboxes, since the keyboard should be used to provide input to the latter.

In this article, we will see how can we use a DropDownList inside a DataGrid. We will use the table, "stores," which is available under the "pubs" database in SQL Server 7 and 2000.

One of the fields in the "stores" table is "state." We will create another lookup table to store the values of states available in United States. We are going to create an editable DataGrid. In view mode, we will have just Labels, but when we switch to edit mode, we will allow the user to modify the state by means of a DropDownList.

I assume that the reader knows how to create a simple DataGrid with TemplateColumn and ItemTemplate tags.

Things that we will be learning in this article
  1. How to populate a DataGrid.
  2. How to populate a DropDownList within a DataGrid.
  3. How to pick the selected item from a DropDownList.
  4. How to preset items in a DropDownList that is in edit mode.

Populating the DataGrid

For our example, we will take the STORE table in the PUBS database. Since stored procedures are very much better than inline query, we use a stored procedure called, sp_stores_sel, which contains a single SQL statement. The SQL statement would be Select * from stores.

How to populate a DropDownList within a DataGrid

The important aspect that is to be noted is that we cannot explicitly bind the DropDownList from the Page_Load event or any other method. The DropDownList control in an EditTemplateColumn is only accessible to the Update method, which is specified in the OnUpdateCommand event.

But, while declaring the DropDownList, we can invoke a method that will return the data source for the DropDownList. We should also specify values for the properties DataTextField and DataValueField. The contents of the field specified in DataTextField will be used to fill the text section of the combo box. And the property, DataTextValue, will be used to fill the value property of the combo box (HTML Select tag).

EditItemTemplate of the DataGrid
    <EditItemTemplate>
        <asp:Label ID="lblTempState"
            Text='<%# DataBinder.Eval(Container.DataItem, "state") %>'
            Runat=server />

        <asp:DropDownList id="cboState"
            DataSource="<%# BindState() %>"
            DataTextField="Statename"
            DataTextValue="Statename"
            runat="server" />
    </EditItemTemplate>

How It Works

The most important piece of code in the above example is DataSource="<%# BindState() %>". We invoke a method called BindState that in turn will return the data source for the DropDownList. We will be looking into this method shortly. Also, we need to specify the text that will be displayed in the DropDownList and the value for each option. We can assign the text by setting the DataTextField property, and the value can be specified using the DataValueField property. We have to specify the field names for both the fields. In our example, we use the "StateName" field for both properties.

DataSource for the DropDownList
    Private Function BindState()
        Dim myConnection As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
        Dim myCommand As SqlCommand = New SqlCommand("sp_das_state_sel", myConnection)

        myCommand.CommandType = CommandType.StoredProcedure

        myConnection.Open()
        Return myCommand.ExecuteReader(CommandBehavior.CloseConnection)
    End Function

How It Works

The BindState method executes a stored procedure called sp_das_state_sel. The last statement in this method, the return statement, actually returns a data source. This is how we set the DataSource property for the DropDownList, which is in the edit mode of a DataGrid. The above sample did not have any error handling, but I have provided the entire aspx page at the download section. You can also see the sample output and a demo.

How to Pick the Selected Item from a DropDownList

In this last section we will see how to get the selected/updated item from the DropDownList. We know that we show the DropDownList only during edit mode. When the user clicks the update button, we have to get the selected item in the combo box. The following two lines of code do this. First let us take a look at the code.

Dim cboStateTemp As DropDownList = CType(e.Item.FindControl("cboState"), DropDownList)
Dim strTemp as String = cboStateTemp.SelectedItem.Value

How It Works

First we use the Findcontrol method to get the combo box object. After the first statement, we have a DropDownList object named "cboStateTemp." Note the type casting done using the CType method.

Once we have a DropDownList object, we can work with all properties and methods that are available in in this object. The property to get the selected value is SelectedItem. We need the value, so we have to say, SelectedItem.Value. If you need the text, then you have to say, SelectedItem.Text.

How to Preset Items in a DropDownList (In Edit Mode)

This is the most tricky part of this article. The event that will be helpful for us to do this operation in is the ItemDataBound event. So, in the datagrid you should invoke a method for this event. Then, in the event all we need is to find the control "cbostate" and set the SelectedIndex property.

Apart from this we need to know which item we need to preset. Well, we can get this value from the edit event. If you do a FindControl on the Edit event for the column that we need the value for (in our case, the "state" column), we will get the value that needs to be preset. Plese see the following piece of code in the ItemDataBound event.

ItemDataBound Event
Private Sub DG_ItemDataBound(s as object, e as DataGridItemEventArgs)
    If e.item.itemType = ListItemType.EditItem Then
        Dim myDropDown as DropDownList
        myDropDown = Ctype(e.Item.FindControl("cbostate"), DropDownList)
        myDropDown.SelectedIndex = myDropDown.Items.IndexOf(myDropDown.items.findbytext(strCurrentState))
    End If
End Sub

How It Works

In the above event we just have three lines of code. The first two statements inside the If statement is pretty straight forward. The third one is the important line, which presets the item in the combo box. The string variable, strCurrentState is populated in the Edit event and is a class variable. You can download the complete code later in this article.

Sample output of our scenario

DataGrid with Combo box - 7973 bytes
Fig: DataGrid with Combo Box.

Test this Script

Download the code

Click here to download the ASPX page
Click here to download the Stored Procedure

Conclusion

I have used stored procedures in all places. For your convenience, I have also included source code for these stored procedures. If you have any questions regarding this article or any of my article please feel free to email me at das@aspalliance.com

Links

How to Edit a DataGrid?
How to capture a Double Click event in DataGrid?
Checkbox Web Server Control
Retrieving Images from SqlServer in ASP .NET
Retrieving Images from SqlServer and displaying it in DataGrid

Send your comments to das@aspalliance.com        



User Comments

Title: about article   
Name: snehasis mishra
Date: 2007-11-03 1:32:51 AM
Comment:
Hi das,

Actually u r doing a fentastic job over here.actually upeople are doing the half works of software proffesionals.


thanks&Regards
snehasis mishra
Title: datagrid and dropdownlist   
Name: Surender
Date: 2007-06-07 5:50:04 AM
Comment:
Hi das,

first of all I thank you very much.....
it is very useful....

thanks & regards
surender
Title: Useful article   
Name: FY Lai
Date: 2007-05-24 4:49:55 AM
Comment:
Thanks for the article, it resolve my problems, brilliant!!
Title: Excellent Article   
Name: Ram
Date: 2007-02-21 4:34:57 PM
Comment:
Excellent
Title: It is file article   
Name: Anulesh
Date: 2006-08-24 3:22:34 AM
Comment:
Thank for this articles, this is very useful,By using this I saved lot of time....♫
Title: Code in C#   
Name: Susan
Date: 2006-08-01 10:42:13 AM
Comment:
Can you translate your code

Dim cboStateTemp As DropDownList = CType(e.Item.FindControl("cboState"), DropDownList)
Dim strTemp as String = cboStateTemp.SelectedItem.Value

into C# for me please? Thank you.
Title: Working with DropDownLists in DataGrids   
Name: Subhajit
Date: 2006-06-08 3:41:36 AM
Comment:
Thenk you very much for this article.
Title: Working with DropDownLists in DataGrids   
Name: Nari
Date: 2006-05-17 7:03:00 AM
Comment:
Its nice
Title: its ok   
Name: korhan
Date: 2005-08-22 11:47:52 AM
Comment:
how can you add a client side script to dropdownlist that writes its selectedvalue in a textbox at the same row?

thanx
Title: Joe   
Name: Joe
Date: 2005-07-26 5:43:50 PM
Comment:
Thanks 4 this.......
Title: DataGrid and DropDownLists:   
Name: Jose-Pablo Lopez
Date: 2005-06-22 12:04:44 PM
Comment:
This article has been very usefull to me, but I'll like to know if is possible to have two independent dropdownlists in the same datagrid.
I have my two dropdowns working but de second one keeps the selectexindex of the first one.
How can I fix that problem?.
Thanks
Title: Excellent Article   
Name: Ezequiel Valencia
Date: 2005-05-04 3:03:58 AM
Comment:
Thenk you very much for this article, ItemDataBound Event was very useful . I save a lot of time with this sample.

Best Regards,

Product Spotlight
Product Spotlight 





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


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