1

How do i create a new Button/Canvas with a dynamic name?

Button {buttonname read from text file} = new Button;

I have googled this for a while now but i can't find the solution.

Thank you!

3
  • Are you have list name? Commented Jun 16, 2016 at 8:35
  • What list name do you mean? if i create a list<> it will solve my problem? Commented Jun 16, 2016 at 8:35
  • you want setting name of control, same that : var button = new Button(); button.Name = "test". Right? Commented Jun 16, 2016 at 8:38

2 Answers 2

2

I'm not sure if I understood correctly, but that name in your example is not the button name, it's just the reference name used in code to access the button. The button name would be set like this:

buttonRefName.Name = "ButtonName1";

So you can set the name to whatever you want: dynamically generated names inside a loop, names read from a file, etc...

You can use the same reference name for multiple buttons, just be sure to add it to List or to WPF Window, Panel, etc... before creating the new one:

var buttonList = new List<Button>();
var buttonRef = new Button { Name = "YourButtonName" };
buttonList.Add(buttonRef);
buttonRef = new Button { Name = "YourButtonName2" };
buttonList.Add(buttonRef);
Sign up to request clarification or add additional context in comments.

2 Comments

The problem is, i dont know how many buttons there might be, so i can't (?) point to them later on. Like click event get cant point to "YourbuttonName" + i (where i is usual counter), can it?
Not sure I understand what you mean, but you can point to them later. You can search the list using the button name to get a reference to the Button you want. Or you can attach the same click event to the button before creating the new one, and in the method you'll get the sender of the event. You can cast it to a Button and verify the name.
1

It not possible the way you want to do it. If you are reading from a text file better use a List or better a Dictionary... an example use is as follows:

var buttons = new Dictionary<string, Button>();
buttons["yourName"] = new Button();
// logic goes here

1 Comment

How can i reach that button later on?

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.