获取事件的控件名称
在我的 C# Windows 窗体表单中,我有一些动态生成的按钮。我在点击事件上分配了以下方法。是否可以获取触发事件的按钮的名称?
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)
{
//handle the exception
}
}
In my C# Windows Forms form I have some buttons which are dynamically generated. I assigned the following method on the click event. Is it possible to get the name of the button from which the event is triggered?
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)
{
//handle the exception
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
sender
参数。这是引发单击事件的控件(在本例中为按钮):注意:如果您已将其他控件(例如面板等)订阅到同一事件处理程序,则可以使用以下命令检查发送者是否是按钮as 运算符:
You can use the
sender
argument. That is the Control (the button in this case) that has raised the click event: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
as
operator:事件处理程序的第一个参数,“
对象发送者
”,包含引发/触发事件的对象/控件的引用。The first argument of the event handler, "
object sender
", contains a reference of an object/control which raised/fired an event.