[英]C# pass a string on an onClick event of a button
Ok, I am not sure how to do this as I am trying to teach myself C# and create a program for work at the same time. 好的,我不确定如何执行此操作,因为我试图自学C#并同时创建一个工作程序。
I have a List of IP addresss: 我有一个IP地址列表:
List<IPAddress> addresses
I have a group of buttons being created for these ip addresses dynamically on the fly once the list is submitted to the form. 一旦列表提交到表单,我就会动态为这些ip地址动态创建一组按钮。
I want to pass a string of text associated to the button (the IPAddress) to the onclick event. 我想将与按钮(IP地址)关联的文本字符串传递给onclick事件。
Button b = new Button();
b.Text = "Router\n\r" + String.Format("{0}.{1}.{2}.126", ba[0], ba[1], ba[2]);
b.Dock = DockStyle.Fill;
b.Click += btnRouter_Click;
b.Size = new System.Drawing.Size(150, 50);
tlp.Controls.Add(b, 1, 0);
When the button is clicked I want it to launch a command line argument to call putty.exe and go out to a version of the IP address that it was passed when this button was dynamically created, namely the xxx126 address. 单击该按钮时,我希望它启动命令行参数来调用putty.exe,并转到动态创建此按钮时传递的IP地址版本,即xxx126地址。
My onClick Stub right now is: 我现在的onClick存根是:
private void btnRouter_Click(Object sender, EventArgs e)
{
MessageBox.Show("You clicked the Router button!");
}
what I would like is something like: 我想要的是这样的:
private void btnRouter_Click(Object sender, EventArgs e)
{
myProcess.StartInfo.FileName = "Putty.exe";
myProcess.StartInfo.Arguments= "xxx.xxx.xx.126"
Process.Start(myProcess.StartInfo)
}
Only I don't know how to get that string to the button onclick event since it isn't passes by Object or EventArgs. 只有我不知道如何将该字符串传递给按钮onclick事件,因为它不是由Object或EventArgs传递的。
As a quick solution, you could do 作为快速解决方案,您可以
Button b = new Button();
...
b.Tag = "my string";
And then within the event handler 然后在事件处理程序中
private void btnRouter_Click(Object sender, EventArgs e)
{
MessageBox.Show((string)((Button)sender).Tag);
}
Or, as @paqogomez suggested, you may just use Text
value instead of using Tag
(if you do not mind to get the address prefixed with "Router\\n\\r"
: 或者,按照@paqogomez的建议,您可以只使用
Text
值而不使用Tag
(如果您不介意使用"Router\\n\\r"
作为前缀的地址:
private void btnRouter_Click(Object sender, EventArgs e)
{
MessageBox.Show((string)((Button)sender).Text);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.