获取控件名称为事件 [英] Getting control name for an event

查看:72
本文介绍了获取控件名称为事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的C#的winform我有一些按钮这是动态生成。我分配了Click事件中梅索德。是否有可能获得按钮从中触发事件的名称。如果有任何身体知道PLZ份额....

 私人无效btnBrowsDoc_Click(对象发件人,EventArgs五)
$ { b $ b试
{
如果(openFileDialog1.ShowDialog()。等于(DialogResult.OK))
{
gbxDocument.Controls [txtDocument+计数]。文本=
openFileDialog1.FileName;
}
,否则
{
的回报;
}
}
赶上(异常前)
{
}
}


解决方案

您可以使用发件人的说法,那就是控制(按钮在这种情况下)已经提出的单击事件:

  VAR键=(按钮)发送; 
button.Name ...



NB结果
如果你订阅其他控件(如面板等),以相同的事件处理程序,您可以检查,如果发件人是使用运营商的按钮:

  VAR按钮=发送者的按钮; 
如果(按钮!= NULL)
{
button.Name ...

}


In my c# winform i have some buttons which are dynamically generated. I assigned the following methode on click event. Is it possible to get the name of the button from which the event is triggered. If any body Knows plz share....

private void btnBrowsDoc_Click(object sender, EventArgs e)
{
    try
    {
        if (openFileDialog1.ShowDialog().Equals(DialogResult.OK))
        {
            gbxDocument.Controls["txtDocument" + count].Text =
                openFileDialog1.FileName;  
        }
        else
        {
            return;
        }
    }
    catch (Exception ex)
    {
    }
}

解决方案

You can use the sender argument, that is the Control (the button in this case) that has raised the click event:

var button = (Button)sender;
button.Name ...

N.B.
In case you have subscribed other controls (e.g. panels etc) to the same event handler, you can check if the sender is a button using the asoperator:

var button = sender as Button;
if (button != null)
{
    button.Name ...
    ...
}

这篇关于获取控件名称为事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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