How to simply update a listbox's selected item text?

S

shawn.casey

I've seen this issue posted in the past, but couldn't reply to it
because it was so old. I'm starting a new thread for it.
http://groups.google.com/group/micr...d6b7e3bf989/e60d15e0774836cc#e60d15e0774836cc

<---Cut and paste--->
I've added items to a listbox by calling ListBox.Items.Add(new
MyObject()), where MyObject has overridden ToString to show each item's
display value.

I can't seem to change the DISPLAYED TEXT when I change the object
behind the selected index:

((MyObject)listbox.SelectedItem).mydisplayproperty = "abcdef";

The ListBox display doesn't change, but I know the object is changed
since other buttons that examine the contents of each listbox item see
it changed (and enable/disable their button state). How can I easily
do this? I've tried Refresh, Invalidate, Update methods on the
listbox. No luck.
<---end--->

The answer was:

<---Cut and paste--->
I'm not sure how to force ListBox to reread its items, but you can
simulate the effect by adding and removing the item from the list

MyItem m = (MyItem)listBox1.SelectedItem;
m.MyText = "ABCD";
listBox1.Items.Insert(listBox1.SelectedIndex, m);
listBox1.Items.RemoveAt(listBox1.SelectedIndex);

The procedure shouldn't be noticable to the user.
<---end--->

The problem with this is that the SelectedItem gets removed. I could
store the index and force a selection to the new item, but that causes
two SelectedIndexChanged notifications for the control. If I have some
expensive painting going on, this is unnecessary. There should be a
simpler way.

Someone had an erroneous solution to call Invalidate() on the
control...this only causes a redraw of the control, not a recalculation
of the item's text.
 
D

davorin.mestric

It's a bug, as simple as that.

Besides adding then removing updated items, you can do the rotating
DisplayMember trick:


....
listBoxSomething.DisplayMember = "DummyDisplayString";
listBoxSomething.DisplayMember = "DisplayString";


....DummyDisplayString must be an actuall property on the object,
otherwise this will not work.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top