Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Please anyone can help me out in adding the listbox items into a database table, i used the following code for doing so but it dosent work properly.. (it's a C# windows application)

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;

namespace test
{
public partial class MainForm : Form
{
  public MainForm()
  {
      InitializeComponent();
  }

  void Button1Click(object sender, EventArgs e)
  {
     SqlConnection conn = new SqlConnection(@"User ID=username; Password=pass; 
                    Initial Catalog=databasename; data source=localhost");
     SqlCommand cmd = conn.CreateCommand();
     foreach(object i in listBox1.SelectedItems)
     {
       cmd.CommandText = "INSERT INTO TableName (columnName) VALUES('"+i.ToString()+"')";
       cmd.ExecuteNonQuery();
     }
     conn.Close();
  }
}

Pls can any one help me out as soon as possible......
Posted
Updated 26-Mar-10 21:29pm
v4

Well, what have you tried ? Which of the thousands of online articles on this have you read ? Which of the hundreds of books printed have you read ? How have you tried to do this for yourself before asking us to do it for you ?
 
Share this answer
 
Approach you are following is not good, but still by doing as following your code will work.
foreach(ListItem i in listBox1.SelectedItem)
           {
               cmd.CommandText = "INSERT INTO TableName (columnName) VALUES('"+i.Text)+"')";
               cmd.ExecuteNonQuery();
           }


You can use either i.Text or i.Value as per your requirement.

You should have been done this as following.

Create a XML document for all the items and pass the xml to the DB, so that you can insert all the items in a single datbase trip.
 
Share this answer
 
SqlConnection mycn;
SqlDataAdapter myda;
DataSet ds;
String strConn;
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
strConn="Data Source=localhost;uid=sa;pwd=;Initial Catalog=database";
mycn = new SqlConnection(strConn);
myda = new SqlDataAdapter ("Select * FROM Table ", mycn);
ds = new DataSet();
myda.Fill (ds,"Table");
DropDownList1.DataSource =ds.Tables [0] ;
DropDownList1.DataTextField =ds.Tables[0].Columns["Name"].ColumnName.ToString();
DropDownList1.DataValueField =ds.Tables[0].Columns["Id"].ColumnName.ToString();
DropDownList1.DataBind () ;

}
}
I m giving the code for select check this and try to insert the record .. Hope this will help you.
Good Luck
 
Share this answer
 
v2
Comments
Henry Minute 19-May-10 9:05am    
Reason for my vote of 1
The OP clearly stated it was a Windows Application

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900