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 VB.net
In the previous article I have explained how to to insert multiple selected items of Listbox todatabase as comma separated in ASP.Net using C# and VB.net, how to generatealphabets A to Z in asp.net, how to remove the selected item fromdropdownlist in asp.net using C#, VB.net and how to show the data in Gridviewclient side using Jquery, Json and Ajax.
Implementation:
HTML Markup:
<fieldset style="margin-left: 40px;width:30%">
<legend><strong>Multiple
selected values of ListBox</strong></legend>
<table>
<tr><td>Select Technology
:</td><td> <asp:ListBox ID="lstboxtech"
runat="server"
SelectionMode="Multiple">
<asp:ListItem>Asp.net</asp:ListItem>
<asp:ListItem>Php</asp:ListItem>
<asp:ListItem>Java</asp:ListItem>
</asp:ListBox></td></tr>
<tr><td></td><td> <asp:Button ID="btnsubmit"
runat="server"
Text="Submit"
/></td></tr>
</table>
</fieldset>
Add the
namespace
C#
code:
using
System.Data;
using
System.Data.SqlClient;
using
System.Configuration;
VB.net
code
Imports System.Data
Imports
System.Data.SqlClient
Imports
System.Configuration
Create
sqlconnection
C#
code:
SqlConnection
con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
VB.net
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)
{
try
{
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;
}
else
{
str += "," + lstboxtech.Items[i].Text;
}
}
}
cmd.Parameters.AddWithValue("@technology", str);
con.Open();
cmd.ExecuteNonQuery();
Response.Write("<script>alert('Record Insert
SUccessfully');</script>");
lstboxtech.SelectedIndex = -1;
}
catch (Exception ex)
{ }
}
VB.net
code
Protected Sub btnsubmit_Click(sender As
Object, e As
System.EventArgs) Handles
btnsubmit.Click
Try
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
Else
str += "," + lstboxtech.Items(i).Text
End
If
End
If
Next
cmd.Parameters.AddWithValue("@technology", str)
con.Open()
cmd.ExecuteNonQuery()
Response.Write("<script>alert('Record Insert
SUccessfully');</script>")
lstboxtech.SelectedIndex = -1
Catch
ex As Exception
End Try
End Sub
No comments:
Post a Comment