在表单之间传递值(winforms) [英] passing values between forms (winforms)
问题描述
将值传入和传出第二种形式时的奇怪行为.
Wierd behaviour when passing values to and from second form.
ParameterForm pf = new ParameterForm(testString);
作品
ParameterForm pf = new ParameterForm();
pf.testString="test";
没有(testString 定义为公共字符串)
doesn't (testString defined as public string)
也许我错过了什么?无论如何,我想让第二个变体正常工作,就目前而言 - 它返回空对象引用错误.
maybe i'm missing something? Anyway I'd like to make 2nd variant work properly, as for now - it returns null object reference error.
感谢您的帮助.
在此处发布更多代码:
打电话
Button ParametersButton = new Button();
ParametersButton.Click += delegate
{
ParameterForm pf = new ParameterForm(doc.GetElementById(ParametersButton.Tag.ToString()));
pf.ShowDialog(this);
pf.test = "test";
pf.Submit += new ParameterForm.ParameterSubmitResult(pf_Submit);
};
定义和使用
public partial class ParameterForm : Form
{
public string test;
public XmlElement node;
public delegate void ParameterSubmitResult(object sender, XmlElement e);
public event ParameterSubmitResult Submit;
public void SubmitButton_Click(object sender, EventArgs e)
{
Submit(this,this.node);
Debug.WriteLine(test);
}
}
结果:提交 - 空对象引用测试 - 空对象引用
result: Submit - null object reference test - null object reference
推荐答案
pf.ShowDialog(this);
是一个阻塞调用,所以pf.Submit += new ParameterForm.ParameterSubmitResult(pf_Submit);
永远不会到达:切换顺序.pf.ShowDialog(this);
is a blocking call, sopf.Submit += new ParameterForm.ParameterSubmitResult(pf_Submit);
is never reached: switch the order.Submit(this,this.node);
抛出一个空对象引用,因为没有事件分配给它(见上文).通常,您应该始终首先检查:if (Submit != null) Submit(this,this.node);
Submit(this,this.node);
throws a null object reference because no event is assigned to it (see above). Generally, you should always check first:if (Submit != null) Submit(this,this.node);
你应该改变``pf.ShowDialog(this);
to
pf.Show(this);`,这样你的主窗体就不会在你的对话框打开时被禁用,如果这就是你想要的,或者使用下面的模型(典型的对话框.)You should change ``pf.ShowDialog(this);
to
pf.Show(this);` so that your main form isn't disabled while your dialog box is open, if that's what you want, or use the model below (typical for dialog boxes.)我不确定
pf_Submit
应该做什么,所以这可能不是在您的应用程序中处理它的最佳方法,但它是继续?是/否"问题的一般性问题工作.I'm not sure what
pf_Submit
is supposed to do, so this might not be the best way to go about it in your application, but it's how general "Proceed? Yes/No" questions work.Button ParametersButton = new Button(); ParametersButton.Click += delegate { ParameterForm pf = new ParameterForm(testString); pf.ShowDialog(this); // Blocks until user submits // Do whatever pf_Submit did here. }; public partial class ParameterForm : Form { public string test; // Generally, encapsulate these public XmlElement node; // in properties public void SubmitButton_Click(object sender, EventArgs e) { Debug.WriteLine(test); this.Close(); // Returns from ShowDialog() } }
这篇关于在表单之间传递值(winforms)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!