Friday, March 4, 2016

ASP.Net: Insert multiple selected items of listbox to database as comma separated

In this article I am going to explain how to insert multiple selected items of Listbox to database as comma separated in ASP.Net using C# and

HTML Markup:
<fieldset style="margin-left: 40px;width:30%">
    <legend><strong>Multiple selected values of ListBox</strong></legend>
    <tr><td>Select Technology :</td><td>  <asp:ListBox ID="lstboxtech" runat="server" SelectionMode="Multiple">
    <tr><td></td><td> <asp:Button ID="btnsubmit" runat="server" Text="Submit" /></td></tr>

Add the namespace
C# code:
using System.Data;
using System.Data.SqlClient;
using System.Configuration; code
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Create sqlconnection
C# code:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString()); code
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("connection").ToString())

On button click write the given code
C# code:

protected void btnsubmit_Click(object sender, EventArgs e)
            SqlCommand cmd = new SqlCommand("Insert into Tb_Technology(Technology) values(@technology)", con);
            String str = "";
            for (int i = 0; i <= lstboxtech.Items.Count - 1; i++)
                if (lstboxtech.Items[i].Selected)
                    if (str == "")
                        str = lstboxtech.Items[i].Text;
                        str += "," + lstboxtech.Items[i].Text;
            cmd.Parameters.AddWithValue("@technology", str);
            Response.Write("<script>alert('Record Insert SUccessfully');</script>");
            lstboxtech.SelectedIndex = -1;
        catch (Exception ex)
        { }
    } code
    Protected Sub btnsubmit_Click(sender As Object, e As System.EventArgs) Handles btnsubmit.Click
            Dim cmd As New SqlCommand("Insert into Tb_Technology(Technology) values(@technology)", con)
            Dim str As [String] = ""
            For i As Integer = 0 To lstboxtech.Items.Count - 1
                If lstboxtech.Items(i).Selected Then
                    If str = "" Then
                        str = lstboxtech.Items(i).Text
                        str += "," + lstboxtech.Items(i).Text
                    End If
                End If
            cmd.Parameters.AddWithValue("@technology", str)
            Response.Write("<script>alert('Record Insert SUccessfully');</script>")
            lstboxtech.SelectedIndex = -1
        Catch ex As Exception
        End Try
    End Sub

No comments:

Post a Comment