How to make ListBox refresh an item's text when the item object ischanged?

S

Sin Jeong-hun

class SomeClass
{
...
public override string ToSting
{
.... return different values according to its state.
}
}

in the form's code

SomeClass s = new SomeClass();
MyListbox.Items.Add(s);

If I add it like that, the Listbox will use ToString() method to
display the SomeClass. But the problem is when the SomeClass's inner
state has changed and therefore ToString() value is changed, the
Listbox doesn't reflect the change automatically. What could be the
best clean solution? The only way I can think of is not to add the
SomeClass directly, but add its ToString() value to the Listbox and
maintain an independent list of SomeClass'. Then when the SomeClass is
changed I may manually change the item with the SomeClass's newest
ToString() value.

But I'm not sure it's the best way. Isn't there any better way like,
ListBox.UpdateItemText(int index) or interface
ListBox.NotifiableObject (I made them up, they are not real)?
 
J

Jeff Johnson

class SomeClass
{
...
public override string ToSting
{
... return different values according to its state.
}
}

in the form's code

SomeClass s = new SomeClass();
MyListbox.Items.Add(s);

If I add it like that, the Listbox will use ToString() method to
display the SomeClass. But the problem is when the SomeClass's inner
state has changed and therefore ToString() value is changed, the
Listbox doesn't reflect the change automatically. What could be the
best clean solution? The only way I can think of is not to add the
SomeClass directly, but add its ToString() value to the Listbox and
maintain an independent list of SomeClass'. Then when the SomeClass is
changed I may manually change the item with the SomeClass's newest
ToString() value.

But I'm not sure it's the best way. Isn't there any better way like,
ListBox.UpdateItemText(int index) or interface
ListBox.NotifiableObject (I made them up, they are not real)?

I would create an event in SomeClass called TextChanged (or just Changed)
and fire that event whenever the text changes. Then in the main form
(whatever owns MyListBox) I'd subscribe to that event and just call
MyListBox.Refresh() whenever that event is fired. You'll need to subscribe
to the event for every SomeClass that gets added to the list box, but you
can point them all to the same event handler. It doesn't sound like you need
to know WHICH SomeClass changed, so your event handler code could look like
this:

private void SomeClass_Changed(object sender, EventArgs e)
{
MyListBox.Refresh();
}
 

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