Reputation: 356
So, I have a form in which all buttons and textboxes and labes are dynamically generated
Code:
private void LoadElements()
{
int Y = 30;
int j = 0;
con.Open();
OleDbCommand populate = new OleDbCommand("SELECT * FROM Users", con);
OleDbDataReader reader = populate.ExecuteReader();
while (reader.Read())
{
b = new Button();
b.Text = "Delete";
b.Name = reader["Username"].ToString();
b.BackColor = Color.DarkOrange;
b.ForeColor = Color.Black;
b.Location = new Point(240, Y);
b.FlatStyle = FlatStyle.Flat;
LB.Add(b);
tb1 = new TextBox();
tb1.Location = new Point(10, Y);
TB1.Add(tb1);
tb1.Text = reader["Username"].ToString();
tb2 = new TextBox();
tb2.Location = new Point(120, Y);
tb2.Text = reader["Password"].ToString();
TB2.Add(tb2);
Y += 30;
j++;
}
foreach (Button BTN in LB) // <- this is a globaly declared List<Button>
{
this.Controls.Add(BTN);
BTN.Click += new EventHandler(BTN_Click);
}
foreach (TextBox text1 in TB1) // <= -||- List<TextBox>
{ this.Controls.Add(text1); }
foreach (TextBox text2 in TB2) // -||-
{ this.Controls.Add(text2); }
// MORE CODE UNDER
}
As you may or may not have noticed, the whole form is a "superadmin" type of form, all users and passwords are loaded from database onto it. I want to be able to have a reference to the created buttons, when a Delete button is clicked I want the program to go into the database and search "WHERE [Username] LIKE" + button.Name + ""(because the button name is the actually Username); My code creates elements dynamically like this: [Name] [Password] [Delete] in the form of [textbox1] [textbox2] [button]. Problem is whenever I click any of the buttons it only takes reference to the last one created, how could I make the event handler so that it can see every button's respective .name?
Upvotes: 2
Views: 125
Reputation: 2397
The pivotal code is in the event handling procedure - you did not show that. Look at the object sender parameter, and use it accordingly!
void BTN_Click(object sender, EventArgs e)
{
Button b = sender as Button;
if (b!=null)
{
//that's your button, with the properties created in the loop.
}
}
Upvotes: 1
Reputation: 1033
It looks like your looking for this code.
b.Click += new EventHandler(b_Click);
Add it into your button creation...
while (reader.Read())
{
b = new Button();
b.Text = "Delete";
b.Name = reader["Username"].ToString();
b.BackColor = Color.DarkOrange;
b.ForeColor = Color.Black;
b.Location = new Point(240, Y);
b.FlatStyle = FlatStyle.Flat;
***b.Click += new EventHandler(b_Click);***
LB.Add(b);
}
Upvotes: 0