What you want to see on DotNetFunda.com ?
DotNetFunda.Com Logo
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 3527 |  Welcome, Guest!   Register  Login
 Home > Code Snippets > ASP.NET > Save more then one select items from listbox to database ...
Lalji_Mer

Save more then one select items from listbox to database

 Code Snippet posted by: Lalji_Mer | Posted on: 5/1/2012 | Category: ASP.NET Codes | Views: 970 | Status: [Member] | Points: 40 | Alert Moderator   


First declare namespaces SqlClient, StrngCollections and StringBuilder built-in methods & use below code.



private string GetConnectionString()
{

//Where DBConnection is the connetion string that was set up in the web config file

return System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;

}
private void InsertRecords(StringCollection sc)
{
SqlConnection conn = new SqlConnection(GetConnectionString());

StringBuilder sb = new StringBuilder(string.Empty);

foreach (string item in sc)

{

const string sqlStatement = "INSERT INTO Table1 (Employees) VALUES";

sb.AppendFormat("{0}('{1}'); ", sqlStatement, item);

}
try

{
conn.Open();

SqlCommand cmd = new SqlCommand(sb.ToString(), conn);

cmd.CommandType = CommandType.Text;

cmd.ExecuteNonQuery();

Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);

}

catch (System.Data.SqlClient.SqlException ex)

{

string msg = "Insert Error:";

msg += ex.Message;

throw new Exception(msg);

}

finally

{

conn.Close();

}

}

protected void Page_Load(object sender, EventArgs e)

{
}

protected void Button1_Click(object sender, EventArgs e)

{
StringCollection sc = new StringCollection();

foreach (ListItem item in ListBox1.Items)

{

if (item.Selected)

{

sc.Add(item.Text);

}

}

InsertRecords(sc);

}



LP MER
Found interesting? Add this to:


>> Write Response - Respond to this post and get points

More codes snippets

About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/22/2013 9:08:14 PM