Hi ,
I m using VS2008 with SQL server 2008 at the backend. I m creating a windows application in which I have 2 listboxes.the data is being retrieved from SQL server database in listbox1.i want to select few itms from this listbox and add them to second one through add button. PROBLEM: the values are being retireved from database but when i click add button after selecting a value from listbox1, System.Data.DataRowView is displayed in listbox2 automatically. listbox2 is not currently connected to any databse. here is the code

for (int i = 0; i < listBox1.Items.Count; i++) 
{ listBox2.Items.Add(listBox1.Items[i]); 
listBox1.Items.Remove(listBox1.SelectedItem); 
} 

i have also tried using this:

for (int i = 0; i < from.SelectedItems.Count; i++) 
{ to.Items.Add(from.SelectedItems[i].ToString()); }
 foreach (var item in new ArrayList(from.SelectedItems)) 
{ from.Items.Remove(item); } 

from and to are listbox1 and listbox2 respectively

any help will be appreciated

Recommended Answers

All 20 Replies

Did you bind the listBox1, using DataSource property from DataTable?
If so, you have to 1st get the item and value from listBox item and add it some other place (in your case to listBox2):

for(int i = 0; i < listBox1.SelectedItems.Count; i++)
{
     DataRowView view = listBox1.SelectedItem as DataRowView;
     string item = view["ColumnNameOfItem"].ToString(); //can be some name
     int value = Convert.ToInt32(view["ColumnNameOfValue"]);  //can be some id (number)
     listBox2.Items.Add(item); // it you want to add item (you can add value as well);
}

ColumnNameOfItem (or OfValue) are the names of fields in your dataTable (and same are in dataBase as well). Insteads of names you can use indexes (0 and 1, but without quotation marks).

Hope it helps.
bye

U came as an angel Mitja Bonca I had been working on it for 3 days...
now i want to remove the selcted itms from listbox 1.
I used the following line within the same for loop and it says

listBox1.Items.Remove(listBox1.SelectedItem);

Items collection cannot be modified when the DataSource property is set

and Yes i had bound the data to the listbox using from datatable usind valumember and displaymember properties.

Sure, you cannot midify the number of item in a collection.
What can we do?
hmmm, let me see...

I think I know...

now i want to remove the selcted itms from listbox 1.
I used the following line within the same for loop and it says

listBox1.Items.Remove(listBox1.SelectedItem);

Items collection cannot be modified when the DataSource property is set

and Yes i had bound the data to the listbox using from datatable usind valumember and displaymember properties.
I m checking this link
http://forums.asp.net/t/1526751.aspx/1
hes got the same problem but his problem is resolved by just using the line of code i have written,. wot cud be done ?

Here, I did the whole you you need:

DataTable table;
        public Form1()
        {
            InitializeComponent();
            table = new DataTable("myTable");
            table.Columns.Add("ID", typeof(int));
            table.Columns.Add("Name", typeof(string));
            //adding some example data:
            for (int i = 0; i < 6; i++)
                table.Rows.Add(i, "name " + i);
            listBox1.DataSource = table.DefaultView;
            listBox1.DisplayMember = "Name";
            listBox1.ValueMember = "ID";
            listBox1.SelectionMode = SelectionMode.MultiSimple;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            List<DataRow> rowsToRemove = new List<DataRow>();
            for (int i = 0; i < listBox1.SelectedItems.Count; i++)
            {
                DataRowView view = listBox1.SelectedItem as DataRowView;
                int id = Convert.ToInt32(view["ID"]);
                string name = view["Name"].ToString();
                //add the id or name to lsitBox2 (or both as DataRow)!

                //then...
                //add row to list:
                rowsToRemove.Add(view.Row);
            }

            //now remove selected rows:
            foreach (DataRow row in rowsToRemove)
                table.Rows[0].Delete();
        }

I almost forgot how to delete rows from listBox - when these are databound!!!
So vote some ++; :)
bye

below is my code for retrieving itms into listbox 1

private void Form1_Load(object sender, EventArgs e)
        {

            string connectionstring = "Data Source = SAMADKHAN; Initial Catalog = Students_Registration; User Id = sa; Password = admin";
            string insert = "SELECT * from Courses";
            SqlConnection con = new SqlConnection(connectionstring);
            SqlDataAdapter da = new SqlDataAdapter(insert, con);
            DataTable dt = new DataTable();
            da.Fill(dt);
            listBox1.DataSource = dt;
            listBox1.ValueMember = "course_id";
            listBox1.DisplayMember = "Course_name";
            listBox1.Refresh();
}

in ur code u r adding dummy values to the table.. but i hv retrieved them from database this is what i want to ask

listBox1.SelectionMode = SelectionMode.MultiSimple;

why have u chosen multisimple selection mode? wot wud it do?

eh, thats only if you want to use the option of choosing more item as a time. By default, you can select only one item.
---------

Dont look about my dummy code. Leave it alone, its there only to run my test code.
But its the same thing; I filled dataTable.
---------

To remove selected items from listBox1 use my code from button1_Click event.

yeah i had posted a reply before running it.i checked it selects multiple rows at a time but it was having problem so i have commented it out..
i have left the dummy coed as it is.. when removing itms from listbox1 it only removes 1st item of listbox1 as there is zeroth index given..
how can I add it to loop?

Did you put all THESE code into button_Click event:

List<DataRow> rowsToRemove = new List<DataRow>(); //add this !!

            for (int i = 0; i < listBox1.SelectedItems.Count; i++)
            {
                DataRowView view = listBox1.SelectedItem as DataRowView;
                int id = Convert.ToInt32(view["course_id"]);
                string name = view["Course_name"].ToString();
                //add the id or name to lsitBox2 (or both as DataRow)!
                listBox1.Items.Add(name); //adding name only!
                //then...
                //add row to list:
                rowsToRemove.Add(view.Row);
            }
 
            //now remove selected rows:                  add this too!!
            foreach (DataRow row in rowsToRemove)
                table.Rows[0].Delete();

Copy paste it as it IS.

Because it works 100%. I tested it.

public partial class Student_Registration : Form
    {
        DataTable dt = new DataTable();
        public Student_Registration()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            string connectionstring = "Data Source = SAMADKHAN; Initial Catalog = Students_Registration; User Id = sa; Password = admin";
            //string insert = "insert into Students values (' fname ',' lname',' id ',' studentclass ',' age'");
            string insert = "SELECT * from Courses";
            SqlConnection con = new SqlConnection(connectionstring);
            SqlDataAdapter da = new SqlDataAdapter(insert, con);
            //DataTable dt = new DataTable();
            da.Fill(dt);
            listBox1.DataSource = dt;
            listBox1.ValueMember = "course_id";
            listBox1.DisplayMember = "Course_name";
            listBox1.Refresh();
           // listBox1.SelectionMode = SelectionMode.MultiSimple;
            listBox2.Items.Clear();
        }

private void button2_Click(object sender, EventArgs e)
        {
            List<DataRow> rowsToRemove = new List<DataRow>();
            for (int i = 0; i < listBox1.SelectedItems.Count; i++)
            {
                DataRowView view = listBox1.SelectedItem as DataRowView;
                string item = view["Course_Name"].ToString(); //can be some name
                //int value = Convert.ToInt32(view["Course_Id"]);  //can be some id (number)
                string value = Convert.ToString(view["Course_Id"]);
                listBox2.Items.Add(item); // it you want to add item (you can add value as well);
                rowsToRemove.Add(view.Row);

            }


            foreach (DataRow row in rowsToRemove)
                dt.Rows[0].Delete();

            }

                           }

Yes, this looks fine, and it has to work.

And if you dont need the value (this is ID column) you can erase this code from the event.

it does work fine as long as adding itms in second listbox is concerned.but when it comes to removing items from 1st listbox, it only removes 1st item from list 1.. although it adds as many itms in listbox2 as we want but removes only the one from the first listbox at the zeroth index..have u tried adding more than item in second listbox?

How many items to you select? More then one?

i m selcting multiple items one by one and clicking add button each time..hence for every click i want selected item to be removed from 1st listbox and to be added to the second listbox. and vice versa

Ups, really sorry, I did a stupid mistake. You were right, it really did remove only one (1st) item.

Check this out now (now I really had to dig into my brains to make it work) :)

List<int> rowIndexes = new List<int>();
            foreach (int index in listBox1.SelectedIndices)
            {
                DataRowView view = listBox1.SelectedItem as DataRowView;
                int id = Convert.ToInt32(view["ID"]);
                string name = view["Name"].ToString();
                //add the id or name to lsitBox2 (or both as DataRow)!
                rowIndexes.Add(index);
            }
            for (int i = rowIndexes.Count; i > 0; i--)
                table.Rows.RemoveAt(rowIndexes[i - 1]);
            table.AcceptChanges();

i wish here was an option for pasting an image so that i would have shown you the condition of my form.. it nopw removes more than one item from listbox 1 but doesnot display anything in the listbox2..

hmm, what abou this:

private void button1_Click(object sender, EventArgs e)
        {
            List<int> rowIndexes = new List<int>();
            foreach (int index in listBox1.SelectedIndices)
            {
                DataRowView view = listBox1.Items[index] as DataRowView;
                int id = Convert.ToInt32(view["ID"]);
                string name = view["Name"].ToString();
                listBox2.Items.Add(name);
                //add row index to list:
                rowIndexes.Add(index);
            }
            for (int i = rowIndexes.Count; i > 0; i--)
                table.Rows.RemoveAt(rowIndexes[i - 1]);
            table.AcceptChanges();
        }

oh it finally worked!!!you are an angel!!
Thankyou very much for your continued replies....
I'll ask more questions tomorrow.. its night here :)

finally :)
but its not a problem, if I started to help you, then I cannot just quit somewhere in the middle of a discusson, or before you dont get what you want it.

PS: you could vote up some posts ++ :)

best regards,
bye

Great Article!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.