Hi people, first post here =]
I have a C#.Net program that has 3 forms ( frmMain, frmPrint, frmAudio.) Each of the three forms have a listbox, frmPrint and frmAudio have values in the listbox which the user can select and then the listbox control on frmMain gets updated with whatever values they select.
I need to do some calcuations on the values that are entered on frmMain listbox. The problem is I can't seem to find the right event so I can calculate these values on the fly whenever the listbox has a item added or removed.
foreach
(object o in lstProducts.Items){
if (o.ToString() == "I Did It Your Way (Print)")txtShipping.Text =
"works";}
I've tried the SelectedIndexChanged and SelectedValueChange and the form_Load and form_enter events with the above code, none work. the selectedIndexChange requires me to click an item in the listbox. This is not what I want.
I want it to automatically and on the fly do the calcuations (or in the above code, display the text in the textbox.)
Am I clear here? Advice/suggestions please.
Jan MontanoPosted Nov 15, 2007, 12:06 AM
Hi Tim,
Welcome! =)
Richard is right. Oddly enough, I can't see any event pertaining to the listbox's add item. One workaround is building a custom control which inherits from ListBox class and putting an ItemAddedEvent in it.
public partial class MyListBox : ListBox
{
public event EventHandler ItemAddedEvent;
public MyListBox()
{
InitializeComponent();
if (ItemAddedEvent == null)
{
ItemAddedEvent = new EventHandler(MyListBox_ItemAddedEvent);
}
}
public void Add(string value)
{
this.Items.Add(value);
ItemAddedEvent(this, new EventArgs());
}
void MyListBox_ItemAddedEvent(object sender, EventArgs e)
{
}
}
To use:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
myListBox.ItemAddedEvent += new EventHandler(myListBox_ItemAddedEvent);
}
private void button1_Click(object sender, EventArgs e)
{
myListBox.Add("Jan");
// instead of calling myListBox.Items.Add("Jan");
}
private void Form1_Load(object sender, EventArgs e)
{
}
void myListBox_ItemAddedEvent(object sender, EventArgs e)
{
MessageBox.Show("New item added");
}
}
Cheers,
Jan
Richard BlythePosted Nov 14, 2007, 11:49 PM
If I understand you correctly, you want an event to fire when an item is added/removed. You are correct in assuming that the listbox control has no event for that operation. However, you can create your own custom event and fire it when you add/remove an item. Is what you need? If so, I will show you how to accomplish this.
Cheers!
Richard