Inserting list box selected values in database
How to insert multiple selected values in list box to different rows (one in each row) in database?
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Pravin GhadgeRank #1,340 · 1.3K reputationPosted Feb 3, 2012, 8:05 AM EST
private void button1_Click(object sender, EventArgs e)
{
for(int i=0;i
{
if(listbox1.Items[i].Selected==true)
{
str = "insert into emp1 values('" + listBox1.Items[i].ToString() + "')";
com = new OleDbCommand(str, con);
com.ExecuteNonQuery();
}
}
MessageBox.Show("Records Added Successfuly ");
}
Satyapriya NayakRank #47 · 31.5K reputationPosted Feb 3, 2012, 2:57 AM EST
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Datagridview_bind
{
public partial class Form1 : Form
{
string ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["dsn"];
OleDbCommand com;
OleDbDataAdapter oledbda;
string str;
DataSet ds;
DataTable dt;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//listBox1.Items.Add("a");
//listBox1.Items.Add("b");
//listBox1.Items.Add("c");
OleDbConnection con = new OleDbConnection(ConnectionString);
con.Open();
str = "select * from emp";
com = new OleDbCommand(str, con);
oledbda = new OleDbDataAdapter(com);
ds = new DataSet();
oledbda.Fill(ds, "emp");
dt = ds.Tables["emp"];
int i;
for (i = 0; i <= dt.Rows.Count - 1; i++)
{
listBox1.Items.Add(dt.Rows[i].ItemArray[0]);
}
con.Close();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(ConnectionString);
con.Open();
str = "insert into emp1 values('" + listBox1.SelectedItem + "')";
com = new OleDbCommand(str, con);
com.ExecuteNonQuery();
con.Close();
MessageBox.Show("Records Successfuly Inserted");
}
}
}
Thanks
Ankita Ankita10 reputationPosted Feb 5, 2012, 12:45 AM EST
VulpesRank #55 · 29.2K reputationPosted Feb 5, 2012, 12:58 AM EST