在表单和UserControl之间传递值 [英] Passing value between forms and UserControl
本文介绍了在表单和UserControl之间传递值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的项目中有多个表单,在主表单中,我有一个UserControl实例,一个按钮和一个标签,当我按下按钮时,打开第二个表单并在标签中设置数据库中的值,在form2中按OK,值将传递到表单1上的标签.
I have in my project multiple forms, In the main form i have an instance of an UserControl, a button and a label, when I press the button is open the second form and set in a label a value from the database, press OK from form2, the value in passed to a label on form 1.
How i can get the same value in a label in my instance of usercontrol?
推荐答案
您需要在UserControl中添加一个事件,并在该事件发生时触发该事件.设置并确认.我们将此事件称为ValueSet
.
You need to add an event to your UserControl and fire this event when a value is set and confirmed. Let''s call this eventValueSet
.
public class ValueSetEventArgs : System.EventArgs {
internal ValueSetEventArgs(string value) { this.fValue = value; }
public string FValue { get {return fValue; } }
string fValue;
} //class ValueSetEventArgs
//...
public class MyUserControl {
//...
public System.EventHandler<ValueSetEventArgs> ValueSet;
void SetValue(string value) {
//do what you already did...
if (this.ValueSet != null)
this.ValueSet.Invoke(this, new ValueSetEventArgs(value));
} //SetValue
} //class MyUserControl
您的表格#1应该将事件处理程序添加到MyCustomControl
的此实例.此事件可以设置标签的值或其他任何值:
You form #1 should add an event handler to this instance of your MyCustomControl
. This event can set the value of your label or whatever else:
class MyForm Form {
public MyForm {
InitializeComponent();
MyUserControl.ValueSet += (sender, eventArgs) => {
MyLabel.Text = eventArgs.Value;
// or whatever else
} //MyUserControl.ValueSet
} //MyForm
//...
// normally called in InitializeComponent,
// I just show it as manual code:
Label MyLabel = new Label();
MyUserControl MyUserControl = new MyUserControl();
} //class MyForm
问题解决了.
Problem solved.
这篇关于在表单和UserControl之间传递值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文