在C#中从字符串变量设置控件事件 [英] Set a control event from string variable in C#

查看:92
本文介绍了在C#中从字符串变量设置控件事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我有一个动态创建的文本框控件!

我想创建一个函数来设置textbox(或任何控件)事件及其委托来自字符串变量。



Hi all,
I have a textbox control which been created dynamically!
I want to make a function to set textbox's (or any control) event and its delegate from a string variables.

void SetEvent(ref Control control, string EventType, string EventDelegate)
{
     //Set control.event += delegate;   event = EventType and delegate = EventDelegate
}





函数调用:



Function call:

SetEvent("TextChanged", "txtBox_TextChanged"); //The function will set the event dynamically according to the parameters (txtBox.TextChanged += new EventHandler(txtBox_TextChanged);)
OR
SetEvent("DataBinding", "txtBox_DataBinding"); //The function will set the event dynamically according to the parameters (txtBox.DataBinding += new EventHandler(txtBox_DataBinding);)





如何实现此程序??????



How can I achieve this procedure??????

推荐答案

动态创建控件时,在客户端上为TextBox设置onchange事件。



您可以按以下方式执行此操作:

Set onchange event on clientside for your TextBox when you create your control dynamically.

You can do that as the follows:
yourTextBox.Attributes.Add("onchange", "alert(this.value);");





也许这可以帮到你:

解析C#代码(作为字符串)并插入其他方法 [ ^ ]



执行包含c#代码的用户提供的字符串 [ ^ ]


void SetEvent(对象控件,字符串eventTypes,字符串EventDelegate)

{

EventInfo ei = control.GetType ()。GetEvent(eventTypes);



MethodInfo mi = this.GetType()。GetMethod(EventDelegate,BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);



代表del = Delegate.CreateDelegate(ei.EventHandlerType,this,mi);



ei.AddEventHandler(control,del);

}
void SetEvent(object control, string eventTypes, string EventDelegate)
{
EventInfo ei = control.GetType().GetEvent(eventTypes);

MethodInfo mi = this.GetType().GetMethod(EventDelegate, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);

Delegate del = Delegate.CreateDelegate(ei.EventHandlerType, this, mi);

ei.AddEventHandler(control, del);
}


这篇关于在C#中从字符串变量设置控件事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆