Click here to Skip to main content
15,908,274 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I am trying to save multiple values selected by user to sql column on button click.
ASP.NET
<asp:ListBox ID="ListBox1" runat="server" Height="149px" SelectionMode="Multiple" Width="113px">
        <asp:ListItem Value="1">Vinz</asp:ListItem>
        <asp:ListItem Value="2">Jhen</asp:ListItem>
        <asp:ListItem Value="3">Chris</asp:ListItem>
        <asp:ListItem Value="4">Shynne</asp:ListItem>
        <asp:ListItem Value="5">Chu</asp:ListItem>
        <asp:ListItem Value="6">Mark</asp:ListItem>
        <asp:ListItem Value="7">Lilian</asp:ListItem>
        </asp:ListBox>
<asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />

C#
protected void Button1_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("INSERT INTO tbl_adsubcategory (ad_id,subcategory) VALUES (@ad_id,@subcategory)", con);
        try
        {
            con.Open();
            for (int i = 0; i < ListBox1.Items.Count; i++)
            {
                cmd.Parameters.AddWithValue("@ad_id", 10012);
                cmd.Parameters.AddWithValue("@subcategory" , ListBox1.Items[i].Value);
                cmd.ExecuteNonQuery();
            }
            con.Close();
        }
        catch (Exception)
        {
            throw;
        }
    }

I want result like this: if user select 3,5 and 7 then result is
ad_id subcategory
10012 3
10012 5
10012 7
Posted
Updated 8-Dec-17 0:58am
v2

1 solution

clear the parameters in each iteration and add validation to check the selection
C#
con.Open();
for (int i = 0; i < ListBox1.Items.Count; i++)
{
    if (ListBox1.Items[i].Selected)
    {
        cmd.Parameters.Clear();
        cmd.Parameters.AddWithValue("@ad_id", 10012);
        cmd.Parameters.AddWithValue("@subcategory" , ListBox1.Items[i].Value);
        cmd.ExecuteNonQuery();
    }
}
 
Share this answer
 
v2
Comments
Raj Negi 7-Jun-14 9:44am    
thank you.
DamithSL 7-Jun-14 9:46am    
you are welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900