Calvin Cutts

Calvin Cutts

  • 1.9k
  • 49
  • 730

Trying to use events to link a listbox to a textbox

Dec 10 2019 4:17 AM
Hi, I will include my VS project in case you want it. It's just a simple little thing, a test really, to try to learn how to do this.
 
 Form1 has a textbox and a button, the button opens form2. On form2 is a bindinglistbox linked to the textbox. When I type in the textbox and press enter it's text content is added to the bindinglistbox on form2. I want to click on an item in the listbox on form2 and have the text in the textbox on form1 change to the text I have selected in the listbox.
 
I want there to be a two way bind between the textbox and the bindinglistbox, I have the textbox linked correctly to the listbox but not the other way round.
 
I need to use an event to do so I believe, but there comes a point where I don't understand what to do next.
 
Here is the eventargs class I made:
 
// this event argument will contain the string clicked
// in the history listbox
public class ListBoxIndexChangedEventArgs : EventArgs
{
      private readonly string _clickedText = "";
      public string ClickedText { get; }
      public ListBoxIndexChangedEventArgs(string str)
      {
         this._clickedText = str;
      }
}
 
Inside my form2 class (where the event will be raised) I declared my event:
 
 public event EventHandler ListBoxIndexChanged;
 
 // method to raise the ListBoxIndexChanged event (user clicked a new item in the list
protected virtual void OnListBoxIndexChanged(ListBoxIndexChangedEventArgs e)
{
   ListBoxIndexChanged?.Invoke(this, e);
}
Then in the listbox's SelectedIndexChanged event on form2 I added: 
 
OnListBoxIndexChanged(new ListBoxIndexChangedEventArgs(lstbHistory.Text));
 
I can't figure out what to do next though, someone advised me to do this: "The only thing remains is after you created form2, and before you show it, add an event handler like : form2.ListBoxIndexChanged += (s,e)=> { // do sth with e.ClickedText};" 
 
If someone could help me to do this I would be very grateful,
thank you. 

Brought to you by:

Answers (1)