在c#中调用windows窗体后如何返回调用方法?
我有一个方法,在类a中调用一个新的Windows窗体。在新窗体中,我使用下拉菜单并将下拉菜单中的选定项存储在变量中,称为在c#中调用windows窗体后如何返回调用方法?,c#,.net,winforms,C#,.net,Winforms,我有一个方法,在类a中调用一个新的Windows窗体。在新窗体中,我使用下拉菜单并将下拉菜单中的选定项存储在变量中,称为selectedItem。现在我必须在类a中访问此selectedItem。我使用以下代码 public class A { public method callingmethod() { ExceptionForm expform = new ExceptionForm(); expform.Show(); st
selectedItem
。现在我必须在类a中访问此selectedItem
。我使用以下代码
public class A
{
public method callingmethod()
{
ExceptionForm expform = new ExceptionForm();
expform.Show();
string newexp = expobj.selectedexception;
}
}
我的新代码
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;
}
}
现在,单击提交按钮后,我在selectedItem
中获得了正确的值,但我无法将其传递给类A。如何重新运行到类A?使用ShowDialog()
方法
expform.ShowDialog();
string newexp = expobj.selectedexception;
如果您可以通过禁用父窗体来过帐
例外窗体
,请转到ShowDialog
。但是,如果您不希望禁用的父窗体并继续作为新的独立窗口弹出ExceptionForm
,请尝试将事件返回到父窗体。这里,我展示了一个如何做到这一点的示例:
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;
}
}
在呼叫课上:
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!
}
}
您是否尝试使用get/set访问器将selectedException设置为属性?请使用
expform.ShowDialog()
而不是Show,否则代码将继续执行。