Ask the DotNetJunkies: How do I add a DropDownList to a DataGrid EditItemTemplate?
By eric neff mcp
Published: 4/9/2001
Reader Level: Beginner
Rated: This article has not yet been rated.
Be the first to rate it!
Tell a Friend
Rate this Article
Printable Version
Discuss in the Forums

Question:

I'm working with a DataGrid. When editing a row, I would like to have one of my fields be a DropDownList. I would much rather be able to bind that DropDownList to a table in a DataSet so when new key/values are setup in the database they flow through to my aspx page without having to fuss with it. Please, example in VB.

David Viñas

Answer:

Adding a DropDownList to a DataGrid requires more effort, but the results are rewarding.

[ Run Sample ]

Binding a DropDownList in a DataGrid requires the use of a DataGrid template. You place a DropDownList in the template the same way you would place an TextBox control.

<asp:TemplateColumn HeaderText="state" SortField="state">
   <template name="ItemTemplate">
     <asp:Label runat="server"
       Text='<%# DataBinder.Eval(Container.DataItem, "state") %>'/>
   </template>
   <template name="EditItemTemplate">
     <asp:DropDownList runat="server"
       DataSource='<%# StateIndex.DefaultView() %>'
       DataTextField="Name"
       SelectedIndex='<%# GetStateIndex(Container.DataItem("state")) %>'
       id="edit_State" />
   </template>
</asp:TemplateColumn>

The asp:TemplateColumn defines the column for use in the DataGrid. I have defined 2 templates for this column. One for display of the data and one for the editable row. The DropDownList determine how the bound data is displayed. The DataSource property points to the DataTable containing the rows. The DataTextField property defines the DataView column to be used for display in the list. The SelectedIndex is the numeric position in the list of the Item to be selected. I have used a function here to return the SelectedIndex based upon the name of the state.

Public Function GetStateIndex(StateName As String) As Integer

   Dim cRow as DataRow
   Dim Index as Int64 = 0

   for each cRow in StateIndex.Rows
     if cRow("Name") = StateName then
       Index= cRow("Id")
       exit for
     end if
   next

   return Index

End Function

This function should be optomized for use with any table data. I merely present it here as an example of using the for each construct to enumerate the rows if a DataTable.

The rest of the code deals with building the DataTable and changing the DataGrid to allow editing.

The tutorial "Working with DataGrid Templates" will provide you with more information on using DataGrid templates.



Marketplace
(Sponsored Links)
What are the green links?
   



 
Copyright © 2007 CMP Tech LLC |
Privacy Policy (4/10/06) | Your California Privacy Rights (4/10/06) | Terms of Service | Advertising Info | About Us | Help