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.