Reputation: 3626
I'm learning how to use Windows Forms currently. I have a main Windows Form (MainForm) that controls everything. At a certain point during execution, I want to open up another Windows Form that contains a Listbox (ListboxForm) and a button (DoneButton) that indicates when the user is done with ListboxForm. I've managed to get ListboxForm to show up, but I'm unsure of how to make MainForm wait and continue execution after the user presses DoneButton.
Right now, when ListboxForm pops up and the user clicks DoneButton, ListboxForm is still displayed and nothing happens. I'm unsure of why this is happening - I have a this.close in the button code for DoneButton.
Here's my code for ListboxForm:
public partial class ListboxForm : Form
{
List<string> _items = new List<string>();
public UpdateGhubAndWebConfigForm()
{
InitializeComponent();
_items.Add("Option 1");
_items.Add("Option 2");
_items.Add("Option 3");
listBox1.DataSource = _items;
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { }
// This is for 'DoneButton'
private void button1_Click(object sender, EventArgs e)
{
LoggingProvider.Log.Info("ListboxForm DoneButton clicked with index: " + listBox1.SelectedIndex.ToString());
DoStuff();
this.Close();
}
private void Form1_Load(object sender, EventArgs e) { }
private void label1_Click(object sender, EventArgs e) { }
public static void DoStuff() { }
}
and MainForm opens/creates a ListboxForm like this:
if(displayListboxForm == true)
{
var listboxForm = new ListboxForm();
listboxForm.ShowDialog();
// Now I want MainForm to wait until the user clicks DoneButton in ListboxForm
MessageBox.Show("User has selected an option from ListboxForm");
}
Upvotes: 0
Views: 52
Reputation: 4119
If you want to listen to any event of a form, you need to subscribe to that delegate, basically, your MainForm creates an instance of your ListboxForm that is the one that has the Button you want to click. Put the visibility of the button public
public Button button1....
then from your method subscribe to the event
if(displayListboxForm == true)
{
var listboxForm = new ListboxForm();
//subscribing to the click event
listboxForm.button1.Click += YourMethod;
listboxForm.ShowDialog();
// Now I want MainForm to wait until the user clicks DoneButton in ListboxForm
MessageBox.Show("User has selected an option from ListboxForm");
}
public void YourMethod(EventArgs e)
{
//your logic here when the button is clicked
}
Hope this helps
Upvotes: 1