Skip to main content
 首页 » 编程设计

c#之自定义用户控件如何将数据发送到托管表单

2024年02月06日10cyq1162

我已经使用 C# 实现了自定义用户控件。这个控件有一个按钮。 然后将控件添加到具有列表框的 WinForm Form1。

问题是:当我单击用户控件中的按钮时,如何在列表框中添加一些值?

请您参考如下方法:

当您单击按钮时,您必须从用户控件引发一个事件,然后在您的 form1 中捕获它。

你可以这样做:

用户控制

public event EventHandler CLickFromUserControl; 
 
private void click_event_on_the_button() 
{ 
    //Null check makes sure the main page is attached to the event 
    if (this.CLickFromUserControl != null) 
       this.CLickFromUserControl(new object(), new EventArgs()); 
} 

Form1

public MyApp() 
{ 
     //USERCONTROL = your control with the CLickFromUserControl event 
     this.USERCONTROL.CLickFromUserControl += new EventHandler(MyEventHandlerFunction_CLickFromUserControl); 
} 
 
public void MyEventHandlerFunction_CLickFromUserControl(object sender, EventArgs e) 
{ 
         //add the value here 
} 

您可以向事件传递更多参数:

this.CLickFromUserControl(new object(), new EventArgs(), param1, param2); 

然后在表单中:

public void MyEventHandlerFunction_CLickFromUserControl(object sender, EventArgs e, string param 1, string param2) 
{ 
         //add the value here 
} 

或

您可以在用户控件上创建属性:

public string Value { 
  get { return textBox1.Text; } 
  set { textBox1.Text = value; } 
} 

然后在表单的事件中从发送者访问它。

您可以查看如何构建事件:msdn