kris

kris

  • NA
  • 26
  • 20.1k

Listbox windows form Application

Apr 11 2014 4:46 AM
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

Answers (12)