Create a new Empty Web Site in Visual Studio 2010 either in Visual Basic or Visual C#.
Add a Web Form in the Web Site and add TextBox, ListBox, Button and Label controls in the Web Form
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple"
Height="100px" Width="90px">
<asp:ListItem>USA</asp:ListItem>
<asp:ListItem>UK</asp:ListItem>
<asp:ListItem>Germany</asp:ListItem>
<asp:ListItem>France</asp:ListItem>
<asp:ListItem>Canada</asp:ListItem>
</asp:ListBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Insert" onclick="Button1_Click" />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
Namespaces used in the code
Visual C#
using System.Data.SqlClient;
using System.Data;
Write below code in Button Click event to get selected ListBox items and insert into SQL Server database.
In below code, I have written a query to insert data into CountryVisited table of Sample database. I have established my connection to SQL Server, created a SqlCommand object and added parameters to command object. Value of CountryVisited parameter is the text we will enter in TextBox. I have used a “For Each” loop to loop through the ListBox and get the selected item. The selected item will be the value of CountryVisited parameter. I have called the ExecuteNonQuery() method for each selected value.
Visual C#
protected void Button1_Click(object sender, EventArgs e)
{
string insertText = "INSERT INTO CountryVisited(PersonName, CountryVisited) Values(@PersonName, @CountryVisited)";
string connString = "Data Source=YourServer;Initial Catalog=Sample;Integrated Security=True";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(insertText, conn);
conn.Open();
cmd.Parameters.Add("@PersonName", SqlDbType.NChar, 20);
cmd.Parameters["@PersonName"].Value = TextBox1.Text;
cmd.Parameters.Add("@CountryVisited", SqlDbType.NChar, 10);
foreach(ListItem item in ListBox1.Items)
{
if(item.Selected)
{
try
{
cmd.Parameters["@CountryVisited"].Value = item.Text;
cmd.ExecuteNonQuery();
Label1.Text = "Data Inserted";
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
}
}
conn.Close();
}