so this code here dynamically adds buttons to my wpf windows application. I cant think of the way in which I can call buttons which actually runat server because they are randomly added.
namespace DynamicButtons
{
public partial class Window1
{
public Window1()
{
this.InitializeComponent();
populateButtons();
}
public void populateButtons()
{
int xPos;
int yPos;
Random ranNum = new Random();
for (int i = 0; i < 4; i++)
{
Button foo = new Button();
Style buttonStyle = Window.Resources["CurvedButton"] as Style;
int sizeValue = ranNum.Next(100);
foo.Width = sizeValue;
foo.Height = sizeValue;
xPos = ranNum.Next(200);
yPos = ranNum.Next(300);
foo.HorizontalAlignment = HorizontalAlignment.Left;
foo.VerticalAlignment = VerticalAlignment.Top;
foo.Margin = new Thickness(xPos, yPos, 0, 0);
foo.Style = buttonStyle;
foo.Name = "button" + i;
foo.Click += new RoutedEventHandler(buttonClick);
LayoutRoot.Children.Add(foo);
}
}
private void buttonClick(object sender, EventArgs e)
{
Button clicked = (Button) sender;
// something like certainWindowsButton((i)<-this has to be based on above code) = clicked.Name();
MessageBox.Show("Button's name is: " + clicked.Name);
}
}
}
Every time the application runs the buttons are randomly assigned, what I want is a way in which I can interact with them from the code behind.
So
foo.Name = "button" + i;
means when or whichever button is clicked a number is assigned to it but how can I interact with that button in the code?
private void buttonClick(object sender, EventArgs e)
{
Button clicked = (Button) sender;
// something like certainWindowsButton((i)<-this has to be based on above code) = clicked.Name();
MessageBox.Show("Button's name is: " + clicked.Name);
}
}
I hope that makes sense.
To give you a sense of whats happening at design level:

Each of these grey squares are buttons each button is randomly assigned its designated name and number and each time the application runs these buttons will be reassigned a different number.
I need a way inwhich when a number is assigned to it I can then fire an event for that button clicked.
So randomly a button has been assigned number 1, take this number 1 and then assign it to
private void buttonClick(object sender, EventArgs e)
if
{
button1_Click = clicked.Name(strip away "button" and make sure the (variableNumber leftover matches button(1)_Click);
}
else
button2
etc etc
Which then fires my button event:
private void button1_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("yay each randomly assigned button now correlates with a real button event");
}
}
}
Is this more what you’re looking for? This takes each buttonNClick handler and creates a button for it. This way you don’t even need the “i”.