How do I return to the caller after calling a Windows form in C #?

I have a method where I call a new Windows Form in class A. And in the new form I use the dropdown menu and store the selected item from the dropdown in a variable called selectedItem

. Now I have to access this selectedItem

in class A. I am using the following code.

public class A
{
    public method callingmethod()
    {
        ExceptionForm expform = new ExceptionForm();
        expform.Show();
        string newexp = expobj.selectedexception;
    }
}

      

And my code is in a new form,

public partial class ExceptionForm : Form
{
    public string selectedexception = string.Empty;
    private void btnExpSubmit_Click(object sender, EventArgs e)
    {
        selectedexception = this.comboBox1.GetItemText(this.comboBox1.SelectedItem);
        this.Close();
        return;
    }
}

      

Now after clicking Submit I get the correct value in selectedItem

, but I couldn't pass it to class A. How do I reconfigure class A?

+3


source to share


2 answers


If you're ok with submitting ExceptionForm

above the parent form by disabling it, go to ShowDialog

. But if you don't want to disable the parent and keep popping up ExceptionForm

as a new and independent window, try reversing to the parent form. Here I show an example on how to do it:

public partial class ExceptionForm : Form
{
    public delegate void SelectValueDelegate(string option);
    public event SelectValueDelegate ValueSelected;

    private void btnExpSubmit_Click(object sender, EventArgs e)
    {
        this.Close();

        if (this.ValueSelected!= null)
        {
            this.ValueSelected(this.comboBox1.GetItemText(this.comboBox1.SelectedItem));
        }

        return;
    }
}

      



And in the class call:

public class A
{
    public method callingmethod()
    {
        ExceptionForm expform = new ExceptionForm();
        expform.ValueSelected += ExceptionForm_ValueSelected;
        expform.Show();
    }

    private void ExceptionForm_ValueSelected(string option)
    {
        string newexp = option;
        // Do whatever you wanted to do next!
    }
}

      

+1


source


Use the method ShowDialog()

.



expform.ShowDialog();
string newexp = expobj.selectedexception;

      

+1


source







All Articles