简体   繁体   中英

Removing Selected Values from ListBox

I am getting collection of values from COL_name and adding each value to The listbox named as lstDisplay ,and the values are getting added.At the same time i need to remove the same values in COl_name from the lstAvailable ListBox,but the values are onli gettin added in lstDispaly ,its not getting deleted from the anotherList box namde as lstAvailable .

            foreach (string drr in COl_name)
            {
                lstDispaly.Items.Add(drr);
                lstAvailable.Items.Remove(drr);
            }

Thank you..

It's means, you have no drr object in lstAvailable. Try to do like this:

foreach (string drr in COl_name)
            {
                lstDispaly.Items.Add(drr);
                lstAvailable.Items.RemoveAt(COL_name.IndexOf(drr));
            }

Or you can try to override Equals() method in you class

ListBox.ObjectCollection.Remove uses Equals to determine if two objects are equal. So if your object (what type is it?) does not override Equals menaingfully you would compare references. If both objects are not the same reference they are not considered equal then.

Another reason could be that the ListBox contains objects that are not strings but you are "removing" strings. Then you could use RemoveAt :

var obj = lstAvailable.Items.Cast<object>()
   .Select((obj, index) => new{ obj, index })
   .FirstOrDefault(x => (x.obj == null ? "" : x.obj.ToString()) == drr);
if(obj != null)
    lstAvailable.Items.RemoveAt(obj.index);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM