Open a new form after selecting an item in the list.

I have a list and a button in my form. The list contains 3 elements: House, People, Outdoor. I also created 3 forms to represent values ​​from a list.

I would like the user to highlight the item in the list, and after clicking the button I would like to open the form selected by the user.

How can i achieve this? I tried this link: Calling a new form by clicking an item in a ListBox , but without any success.

I tried:

public Select() { InitializeComponent(); listBox1.Click += OnListBoxItemClick; } private void OnListBoxItemClick(object sender, EventArgs e) { var form2 = new House(); House.ShowDialog(); } 
  • This would only allow me to open one form. How can I assign different forms to open with different values ​​from a list?
  • I want the form to open after clicking the button, and not the value in the list, how to achieve it?
+4
source share
2 answers

You will need to use the ListBox SelectedItem Property:

 private void button1_Click(object sender, EventArgs e) { switch (listBox1.SelectedItem.ToString()) { case "House": House h = new House(); h.ShowDialog(); break; case "People": People p = new People(); p.ShowDialog(); break; case "Outdoor": Outdoor o = new Outdoor(); o.ShowDialog(); break; } } 
+4
source

You can use Dictionary to map values ​​in selected elements to forms, or perhaps even more efficient functions that a form can create (to provide lazy loading).

 private Dictionary<string, Func<Form>> formMapping = new Dictionary<string, Func<Form>>() { {"House", ()=> new House()}, {"People", ()=> new People()}, {"Outdoor", ()=> new Outdoor()}, }; 

Then you can use this mapping in the click event handler to translate the selected value into the form:

 private void button1_Click(object sender, EventArgs e) { Form newForm = formMapping[listBox1.SelectedValue](); newForm.ShowDialog(); } 
0
source

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


All Articles