Save more then one select items from listbox to database

Lalji_Mer
Posted by Lalji_Mer under ASP.NET category on | Points: 40 | Views : 2097
First declare namespaces SqlClient, StrngCollections and StringBuilder built-in methods & use below code.

[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);

}

[/code]

Comments or Responses

Login to post response