0

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.

I have a List of IP addresss:

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.

I want to pass a string of text associated to the button (the IPAddress) to the onclick event.

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 x.x.x.126 address.

My onClick Stub right now is:

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.

1 Answer 1

4

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 useText value instead of using Tag (if you do not mind to get the address prefixed with "Router\n\r":

private void btnRouter_Click(Object sender, EventArgs e)
{
    MessageBox.Show((string)((Button)sender).Text);
}
Sign up to request clarification or add additional context in comments.

3 Comments

@paqogomez Yep, could be. Updated. Thanks!
@paqogomez I re-read the question, it might be that .Text is not exactly what PO wants due to the "Router\n\r" prefix.
Thanks!!! didn't know about that b.tag. again very new to C#. That was exactly what I needed!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.