Call a new form by clicking an item in a ListBox

I am a student and I am still new to programming. I have a list in my form, and in my list box there is an element or name listed in the list "Eric, Molly, Mel", and when I click "Eric", it should redirect me to a new form containing additional information about " Eric. " How can I invoke a new form using the element specified in the list?

0
source share
4 answers

Assuming you are using WinForms to develop your project, and you have a form called Form1 with a ListBox called listBox1 , you can do this:

 public Form1() { InitializeComponent(); listBox1.Click += OnListBoxItemClick; } private void OnListBoxItemClick(object sender, EventArgs e) { var form2 = new Form2(listBox1.SelectedItem); form2.ShowDialog(); } 

Your Form2 class must have a constructor that accepts the selected element as a parameter.

+5
source
  • Create a Windows Forms application.
  • Put the ListBox on the form.
  • Bind some data source to the ListBox control.
  • Create a new Form named PersonDetailsForm whitch can display user data record information.
  • Sign up for the SelectedIndexChanged event.
  • Put this code in the event handler:

     PersonDetailsForm detailsForm = new PersonDetailsForm(); detailsForm.PersonDataItem = listBox1.SelectedItem; // here is your info about person detailsForm.ShowDialog(); 
+1
source

Try using the ListBox.SelectedIndexChanged event. You should also notice the difference between the Click event and what was mentioned above.

See the MSDN document for more information.

0
source

I provide an example on my blog called

C #: how to load a Winform ComboBox or ListBox and have a unique value associated with the selected item

C # winforms and hidden association tag

Both options can be used ... But the bottom line is that you either load the object tag into the form, and when you select it, run it or have a specialized dictionary that also contains the form. For a complete example, see the links above.

NTN

0
source

Source: https://habr.com/ru/post/1495383/


All Articles