items collection cannot be modified when the datasource property is set listbox c#
I am trying to all items from Listbox1 to Listbox2 but keep getting error, not sure how to fix it.
My code:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace SampleApplication{
public partial class Form1 : Form{
public Form1(){
InitializeComponent();
BindValues();
}
private void BindValues(){
string connectionString = @"";
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
try
{
conn.Open();
cmd = new SqlCommand("StoredProcedure", conn);
cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = cmd;
da.Fill(dt);
listBox1.DataSource = dt;
listBox1.ValueMember = "PO_NUMBER";
listBox1.DisplayMember = "PO Number";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cmd.Dispose();
conn.Close();
}
}
private void btnSelect_Click(object sender, EventArgs e){
try
{
if (listBox1.SelectedItem != null)
{
// checking whether listbix1 has items or not if yes then moving items
listBox2.Items.Add(listBox1.SelectedItem.ToString());
listBox1.Items.Remove(listBox1.SelectedItem.ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
//selecting first item of listbox.
if (listBox1.Items.Count > 0)
listBox1.SelectedIndex = 0;
listBox2.SelectedIndex = listBox2.Items.Count - 1;
}
Thanks
Loading
VulpesPosted Apr 11, 2014, 5:57 AM
Just wondering why you set the DataSource property to null originally? Was this set somewhere else?
VulpesPosted Apr 11, 2014, 6:35 AM
krisPosted Apr 11, 2014, 6:16 AM
Munesh SharmaPosted Apr 11, 2014, 6:00 AM
krisPosted Apr 11, 2014, 5:45 AM
VulpesPosted Apr 11, 2014, 5:43 AM
listBox1.ValueMember = "PO_NUMBER";
listBox1.DisplayMember = "PO Number";
krisPosted Apr 11, 2014, 5:42 AM
VulpesPosted Apr 11, 2014, 5:36 AM
However, rather than do all that, I just wouldn't use data-binding at all - I'd fill the Items collection 'manually'.
To do that remove this line:
listBox1.DataSource = dt;
and replace it with the following:
krisPosted Apr 11, 2014, 5:14 AM
Munesh SharmaPosted Apr 11, 2014, 5:13 AM
krisPosted Apr 11, 2014, 5:10 AM
Munesh SharmaPosted Apr 11, 2014, 4:57 AM
listBox1.DataSource = null;
after this you are doing this..
listBox1.DataSource = dt;