How do I save the DropDownList’s SelectedItem value in the database?

Posted on

Question :

I want to register a client and one of their attributes is sex

Database: sex attribute is nvarchar

ASP.NET: I’m working with a listview to insert client data

<asp:SqlDataSource ID="clientes" runat="server" 
        ConnectionString="<%$ ConnectionStrings:Loja %>"
        ProviderName="<%$ ConnectionStrings:Loja.ProviderName %>"
        SelectCommand="SELECT [Id], [sexo] FROM Cliente ORDER BY Id" 
        InsertCommand="INSERT INTO [Cliente] ([sexo]) VALUES (@sexo)" 
        UpdateCommand="UPDATE [Cliente] SET [sexo] = @sexo WHERE [Id] = @Id" 
        DeleteCommand="DELETE FROM [Doente] WHERE [Id] = @Id">
            <asp:Parameter Name="sexo" Type="String" />
            <asp:Parameter Name="sexo" Type="String" />
            <asp:Parameter Name="Id" Type="Int32" />
            <asp:Parameter Name="Id" Type="Int32" />

    <asp:ListView ID="listaClientes" runat="server" DataKeyNames="Id"



                    <asp:RadioButtonList ID="rblSexo" runat="server"
                        <asp:ListItem Text ="Masculino" Value="1" />
                        <asp:ListItem Text ="Feminino" Value="2" />
                    </asp:RadioButtonList><br />

My question is how will I store in the attribute (sex of DB) what the user selects in the RadioButtonList?

I thought about using:

string = "INSERT INTO [Doente] (sexo) VALUES (@sexo)";
command.Parameters.Add("@sexo", rblSexo.SelectedItem.Value);

In the Inserted Event of sqlDataSource, what do you think?


Answer :

As your field expects a nvarchar , I suppose you want to pass the text “Male” or “Female”, if that is the correct it would be you pass that way.

protected void rblSexo_SelectedIndexChanged(object sender, EventArgs e)
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = myConnString;
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "INSERT INTO [Doente] (sexo) VALUES (@sexo)";
                cmd.Parameters.Add("@sexo", SqlDbType.NVarChar).Value = rblSexo.SelectedItem.Text;
            catch (SqlException sqle)

Just a detail, if you’ve been doing this in the OnSelectedIndexChanged="rblSexo_SelectedIndexChanged event, this causes a row to be inserted in the table each time the user changes the sexo , another OnSelectedIndexChanged will only work if you will declare AutoPostBack="true" .


Since the radio button is a value of 1 or 2, you can change the parameter type to Int32
and your insert would be:

string = "INSERT INTO [Doente] (sexo) VALUES (@sexo)";
command.Parameters.Add("@sexo", Convert.ToInt32(rblSexo.SelectedItem.Value));


Leave a Reply

Your email address will not be published. Required fields are marked *