2013-07-25 25 views
2

我正在C#windows应用程序上工作。我的应用程序从自定义控件库中获取控件(按钮,文本框,富文本框和组合框等),并在运行时将它们动态放置到表单中。我如何创建使用委托的控件的事件处理程序?以及如何在特定的自定义控件点击事件中添加业务逻辑?如何在运行时为动态创建的控件添加事件处理程序?

例如:

我有用户1,用户2,用户3,当USER1登录我想只显示“保存”按钮。当用户2然后只显示“添加和删除”按钮,用户3只显示“添加和更新”按钮。文本框和按钮创建为每个用户登录信息从数据库表中取得。在这种情况下我如何处理不同的事件(添加,保存,更新,删除)的按钮来保存,添加,删除和针对不同用户更新时,动态创建表单控件(保存,添加,删除和更新按钮对象是从同一按钮类)

回答

3
var t = new TextBox(); 
t.MouseDoubleClick+=new System.Windows.Input.MouseButtonEventHandler(t_MouseDoubleClick); 

private void t_MouseDoubleClick(object sender, MouseButtonEventArgs e) 
{ 
    throw new NotImplementedException(); 
} 

它加入双单击事件处理程序,以新的文本框

3

使用匿名方法:

Button button1 = new Button(); 
button1.Click += delegate 
        { 
         // Do something 
        }; 

随着方法:

Button button1 = new Button(); 
button1.Click += button1_Click; 

private void button1_Click(object sender, EventArgs e) 
{ 
    // Do something 
} 

你可以在MSDN Documentation找到进一步的信息。

1

我相信你可以做这样的事情:

if (userCanAdd) 
    container.Controls.Add(GetAddButton()); 
if (userCanUpdate) 
    container.Controls.Add(GetUpdateButton()); 
if (userCanDelete) 
    container.Controls.Add(GetDeleteButton()); 

private Button GetAddButton() { 
    var addButton = new Button(); 
    // init properties here 

    addButton.Click += (s,e) => { /* add logic here */ }; 
    // addButton.Click += (s,e) => Add(); 
    // addButton.Click += OnAddButtonClick; 

    return addButton; 
} 

private void OnAddButtonClick (object sender, EventArgs e) { 
    // add logic here 
} 

// The other methods are similar to the GetAddButton method. 
相关问题