How to set SelectedValue of DropDownList in GridView EditTemplate

Shantanu Gupta picture Shantanu Gupta · Aug 13, 2010 · Viewed 62.3k times · Source

I am trying to do this as asked earlier. The only difference that I found is additional List item that was included in above code.

I tried to use AppendDataBoundItems=true but it is still not working. I also want to set the its default value to the value that was being displayed in label of itemtemplate i.e. DropDownList's SelectedValue='<%# Eval("DepartmentName") %>' but thie property is not available to me in dropdownlist. What could be the reason. ??

<EditItemTemplate>
    <asp:DropDownList ID="ddlDepartment_Edit" runat="server" 
        DataSourceID="dsDepartment_Edit" DataTextField="DepartmentName" 
        DataValueField="PK_DepartmentId">
    </asp:DropDownList>
    <asp:SqlDataSource ID="dsDepartment_Edit" runat="server" 
        ConnectionString="<%$ ConnectionStrings:BlackHillsConnect %>"  
        ProviderName="System.Data.SqlClient" SelectCommand="sp_GetDepartmentDropDown" 
        SelectCommandType="StoredProcedure">
    </asp:SqlDataSource>                                 
</EditItemTemplate>
<ItemTemplate>
    <asp:Label ID="lblDepartmentName" runat="server" Text='<%# Eval("DepartmentName") %>' >
    </asp:Label>
</ItemTemplate>   

I am using GridView

Answer

VinayC picture VinayC · Aug 13, 2010

DataValueField seems to be wrong - shouldn't it be DepartmentId? Similarly, you need to have SelectedValue='<%# Eval("**DepartmentId**") %>' - DepartmentName would be the SeletectText.