With Templatefields it is easy to use a dropdown control for value selection. The problem begins if the field in the table have a value which is not in the list of the dropdown. Databinding fails on runtime.
SelectedValue ='<%# Bind("PostalCode") %>' |
Especially field which contains null values making problems. You need to write code.
1) Remove the Databinding
2) Fill the value in the rowcreatedevent. The following code is searching for the value in the list and select it.
Protected Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) If (e.Row.RowState And DataControlRowState.Edit) <> 0 OrElse (e.Row.RowState And DataControlRowState.Insert) <> 0 Then Try Dim tmp As DropDownList = CType(e.Row.FindControl("drpPLZ"), DropDownList) tmp.DataBind() If Not IsNothing(tmp.Items.FindByValue(DataBinder.Eval(e.Row.DataItem, "postalcode").ToString())) Then tmp.SelectedValue = DataBinder.Eval(e.Row.DataItem, "postalcode").ToString() End If Catch ex As Exception End Try End If End Sub |
Casue you are in the created event the binding of dropdown must be done. You do not neet that if you have a static list of entrys in the dropdownlíst
A part of the HTML of the Gridview
<asp:TemplateField HeaderText="PostalCode" SortExpression="PostalCode"> <EditItemTemplate> <asp:SqlDataSource ID="sqlDSPLZ" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString1 %>" SelectCommand="SELECT DISTINCT PostalCode FROM Customers ORDER BY PostalCode" CacheDuration="600" EnableCaching=true></asp:SqlDataSource> <asp:DropDownList ID="drpPLZ" runat="server" DataSourceID="sqlDSPLZ" DataValueField="postalcode" DataTextField="postalcode" > </asp:DropDownList> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Bind("PostalCode") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> |
The data should be load only once from DB so enable caching or put the sqldatasource outside of the gridview.
3) Save the data
You must hook into the saving process with the Rowupdating event. The parameter NewValues must be set with the SelectedValue from DropDownlist.
Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) e.NewValues( "postalcode") = CType(GridView1.Rows(e.RowIndex).FindControl("drpPLZ"), DropDownList).SelectedValue End Sub |
This sample is tooken from the german community website http://www.devtrain.de