Search code examples
c#asp.netformviewsqlparameter

Passing a DataValueField of a nested Drop Down List to an Update SQL command


I have a dynamic Drop Down List nested in the Edit mode of a FormView. A user can select a value from the DDL and click the Update button to update a row in a database.

  <EditItemTemplate>
 <asp:DropDownList ID="priorityLanguage_DDL" runat="server" DataSourceID="SqlDataSource_Languages" DataTextField="language" DataValueField="ID_language" selectedvalue='<%# Eval("priorityLanguage") %>'>        
 </asp:DropDownList> 

<asp:LinkButton class="btn btn-default" ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update" onclick="UpdateButton_click"/>
</EditItemTemplate>

<asp:SqlDataSource ID="SqlDataSource_membersDetails" runat="server" 
    ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" 
           SelectCommand="SELECT * FROM [editorDetail] WHERE [IDuser]= @IDowner" 
    UpdateCommand="UPDATE [priorityLanguage] = @priorityLanguage_ddl_par WHERE [ID_editorDetail] = @ID_editorDetail">

<UpdateParameters>
                  <asp:Parameter Name="priorityLanguage_ddl_par" Type="Int32" />
               </UpdateParameters>
</asp:SqlDataSource>

My question is how can I pass the DataValueField of the DDL to the Update Command. I tried to pass the value directly on the content page but I couldn't cause the DDL is nested inside a FormView so the controlID couldn't be foud.

I also tried in code behind but I didn't manage to pass an int32 to the parameter DefaultValue.

protected void UpdateButton_click(object sender, EventArgs e)
    {   

        DropDownList priorityLanguage_DDL = FormView3.FindControl("priorityLanguage_DDL") as DropDownList;
        SqlDataSource_membersDetails.UpdateParameters["priorityLanguage_ddl_par"].DefaultValue = (priorityLanguage_DDL.DataValueField);               

    }   

WHAT AM I DOING WRONG???


Solution

  • You need dropdownlist.SelectedValue or dropdownlist.SelectedItem.Value instead of priorityLanguage_DDL.DataValueField The DataValueField is used to assign the column name of datasource to DataValue field. It will give you column name but the the value of that column for selected item from dropdownlist.