Event not firing for dynamically created Label - c#

I have a Windows form with labels and I created a common click event handler for all the labels.
The event is bound from code. Now I need to create some more labels in run-time and bind the same event handler to those dynamically created labels. I tried the following but it didn't work.
private void Ctrl_Click(object sender, EventArgs e)
{
Control control = (Control)sender;
if (control is Label)
{
Label lbl = (Label)sender;
txtCaption.Text = lbl.Text;
cboFont.Text = lbl.Font.FontFamily.Name;
txtSize.Text = lbl.Font.Size.ToString();
chkBold.Checked = lbl.Font.Bold;
txtX.Text = lbl.Location.X.ToString();
txtY.Text = lbl.Location.Y.ToString();
txtWidth.Text = lbl.Width.ToString();
gbLogo.Visible = false;
gbControl.Visible = true;
gbDetail.Visible = false;
}
}
private void btnAddDynamic_Click(object sender, EventArgs e)
{
Label label = new Label();
int count = pl.Controls.OfType<Label>().ToList().Count;
label.Location = new Point(50, (25 * count) + 2);
label.AutoSize = true;
Graphics g = label.CreateGraphics();
label.Width =Convert.ToInt32(g.MeasureString(label.Text, label.Font).Width);
label.Name = "label_" + (count + 1);
label.Text = "label " + (count + 1);
label.TabIndex=0;
label.Click += new EventHandler(this.Ctrl_Click);
pl.Controls.Add(label);
}

Related

When generating multiple buttons in C# how do I give each one a separate function?

In my code, I generate one extra label and button every time a different button is clicked. I want it so each button can be programmed with a different function. Ex: If I clicked on generated button1 I would be brought to page 1. If I clicked on generated button2 I would be brought to page 2 etc. What would be the best way to approach this?
Here is my code below:
if (task1 == false)
{
Label taskLabel = new Label();
taskLabel.Text = taskInput.Text;
taskLabel.Location = new Point(63, 183);
taskLabel.BorderStyle = BorderStyle.FixedSingle;
taskLabel.AutoSize = true;
page2.Controls.Add(taskLabel);
labelHeight = taskLabel.Bottom;
labelWidth = taskLabel.Right;
Button taskButton = new Button();
taskButton.Text = "Let's Go";
taskButton.Location = new Point(labelWidth + 30, 180);
taskButton.AutoSize = true;
page2.Controls.Add(taskButton);
taskInput.Text = "";
task1 = true;
}
else
{
Label taskLabel = new Label();
taskLabel.Text = taskInput.Text;
taskLabel.Location = new Point(63, labelHeight + 30);
taskLabel.BorderStyle = BorderStyle.FixedSingle;
taskLabel.AutoSize = true;
page2.Controls.Add(taskLabel);
Button taskButton = new Button();
taskButton.Text = "Let's Go";
labelHeight = taskLabel.Bottom;
labelWidth = taskLabel.Right;
taskButton.Location = new Point(labelWidth + 30, labelHeight - 18);
taskButton.AutoSize = true;
buttonHeight = taskButton.Top;
page2.Controls.Add(taskButton);
taskInput.Text = "";
After you create the button you add a handler to the function that you want it to run.
Button taskButton = new Button();
taskButton.Click += FunctionYouWantToRun();
You can set the click handler for each button you create like this
Button taskButton1 = new Button;
taskButton1.Click += taskButton1_Click;
private void taskButton1_Click(object sender, EventArgs e)
{
// code for the first button
}
Button taskButton2 = new Button;
taskButton2.Click += taskButton2_Click;
private void taskButton2_Click(object sender, EventArgs e)
{
// code for the second button
}
If you have many buttons you could assign them all the same click event and in that click event determine which button was clicked
Button taskButton1 = new Button;
taskButton1.Tag = 1;
taskButton1.Click += taskButton_Click;
Button taskButton2 = new Button;
taskButton2.Tag = 2;
taskButton2.Click += taskButton_Click;
Button taskButton3 = new Button;
taskButton3.Tag = 3;
taskButton3.Click += taskButton_Click;
private void taskButton_Click(object sender, EventArgs e)
{
if ( ((Button)sender).Tag == 1) then
{
// code for the first button
}
else if ( ((Button)sender).Tag == 2) then
{
// code for the second button
}
else if ( ((Button)sender).Tag == 3) then
{
// code for the third button
}
}
or without using the Tag property
Button taskButton1 = new Button;
taskButton1.Click += taskButton_Click;
Button taskButton2 = new Button;
taskButton2.Click += taskButton_Click;
Button taskButton3 = new Button;
taskButton3.Click += taskButton_Click;
private void taskButton_Click(object sender, EventArgs e)
{
if (sender == Button1) then
{
// code for the first button
}
else if (sender == Button2) then
{
// code for the second button
}
else if (sender == Button3) then
{
// code for the third button
}
}

Dynamically created combobox SelectedIndexChanged not adding controls

I'm trying to have panel displaying the result differently each time a user select items from pre-loaded combobox and dynamically created combobox.
Initially it will load a comboBox with item of ("HelloWorld"), each time when I do a SelectedIndexChanged with "HelloWorld", the panel will show 1.
However, problem lies on whenever I hit on add button and do SelectedIndexChanged with "HelloWorld" on the newly created button. It simply doesn't show 2 but instead when I hit on pre-loaded comboBox, it show 3.
Is it something to do with life-cycle events?
class form{
int index = 0;
private void formMain_Load(object sender, EventArgs e)
{
Button add = new Button();
panel.Controls.Add(search());
add.Click += new EventHandler((object o, EventArgs e) => { panel.Controls.Add(search()); });
panel.Controls.Add(add);
}
public ComboBox search()
{
ComboBox searchField = new ComboBox();
searchField.Items.Add("HelloWorld");
searchField.SelectedIndexChanged += new EventHandler((object io, EventArgs ie) =>
{
index++;
Label display = new Label();
display.Text = index.ToString();
panel.Controls.Add(display);
});
return searchField;
}
}
I have tried many days and couldn't understand it ... Any helps would be appreciated. Thanks
int index { get; set; }
public Form2()
{
InitializeComponent();
index = 0;
Button add = new Button();
add.Text = "Add";
add.Location = new Point(search().Location.X + search().Width + 10, search().Location.Y);
panel.Controls.Add(search());
add.Click += new EventHandler((object o, EventArgs e) => {
panel.Controls.Add(search());
});
panel.Controls.Add(add);
}
public ComboBox search()
{
ComboBox searchField = new ComboBox();
searchField.Items.Add("HelloWorld");
searchField.Name = "cmb " + index.ToString();
searchField.Location = new Point(10, (index + 1) * 20);
searchField.SelectedIndexChanged += new EventHandler((object io, EventArgs ie) =>
{
index++;
Label display = new Label();
display.Location = new Point(250, search().Location.Y-12);
panel.Controls.Add(display);
display.Text = index.ToString();
});
return searchField;
}

How to change button color on button click in C#?

I am creating an online test application, in which I am generating approximately 100 buttons at run time on form load. Here is the piece of code:w
private void addQuestion_Reviewbutton()
{
for (int i = 1; i <= clsGlobalVars.gnTotalQuestion; i++)
{
Button button = new Button();
button.Location = new Point(160, 30 * i + 10);
button.Click += new EventHandler(ButtonClickOneEvent);
button.Tag = i;
button.Name = "Question" + i;
button.Text = i.ToString();
button.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.button));
button.BackgroundImageLayout = ImageLayout.Stretch;//.Zoom;
button.FlatAppearance.BorderSize = 0;
button.Size = new System.Drawing.Size(47, 41);
button.BackColor = Color.Transparent;
button.FlatStyle = FlatStyle.Flat;
button.Font = new System.Drawing.Font("Segoe UI Semibold", 12);
button.ForeColor = Color.White;
button.Cursor = Cursors.Hand;
flowLayoutPanel1.Controls.Add(button);
}
}
and on this button click, I am changing the background-color.
void ButtonClickOneEvent(object sender, EventArgs e)
{
Button button = sender as Button;
//button.BackColor = Color.Yellow;
button.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.button_Orange));
lblQuestionNo.Text = ((int)button.Tag).ToString()+".";
btnNext.Focus();
}
I have a button on the form Named "Next". Now my problem is that if I am currently in question "1." and I press the button next I want to change the background image of the button whose text is "2".
Yo check this !
tldr; the guidance are
Is the click event go to ButtonClickOneEvent ?
How to call other button
...
profit?
protected void Page_Load(object sender, EventArgs e)
{
addQuestion_Reviewbutton();
}
void ButtonClickOneEvent(object sender, EventArgs e)
{
Button button = sender as Button;
var currentbtn_id = button.ID;
int nextid = Convert.ToInt32( currentbtn_id.Substring("Question".Length)) + 1;
var nextBtn = flowLayoutPanel1.FindControl("Question"+ nextid.ToString() );
(nextBtn as Button).BackColor = Color.Red;
}

How do I delete a a label/button based on its name? WPF Visual Studio 2015

I'm trying to delete a label and a button based on their name but unfortunately the option to remove them (that I know of) is through Children.Remove where it only accepts the actual label/button itself and not their name. I needed the name since it's the one that determines which X button belongs to who.
Label labels;
Button buttons;
int counter;
private void button_Copy_Click(object sender, RoutedEventArgs e)
{
counter++;
Label lbl = new Label();
lbl.Content = counter.ToString();
lbl.HorizontalAlignment = HorizontalAlignment.Center;
lbl.VerticalAlignment = VerticalAlignment.Center;
lbl.FontSize = 50;
lbl.Name = "lbl" + counter;
labels = lbl;
Button bt = new Button();
bt.Content = "X";
bt.HorizontalAlignment = HorizontalAlignment.Right;
bt.VerticalAlignment = VerticalAlignment.Top;
bt.Name = "btn" + counter;
buttons = bt;
bt.Click += Button_Click;
grid.Children.Add(lbl);
grid.Children.Add(bt);
}
private void Button_Click(object sender, EventArgs e)
{
grid.Children.Remove(labels.Name = "btn" + counter);
grid.Children.Remove(buttons);
}
The grid.Children.Remove(labels.Name = "btn" + counter); is not correct but hopefully it tells how I kinda wanted it to happen.
You can first get the child element using a LINQ Where expression:
var child = grid.Children.OfType<Control>().Where(x => x.Name == "btn" + counter).First();
And then call Remove:
grid.Children.Remove(child);

Making labels in array change backcolor on click using C# in Windows Forms

How can I change the BackColor of a label in an array when I click on it? Since there are multiple elements, I cannot manually activate each event for each individual label.
for (int i = 0; i < 361; i++)
{
board[i] = new Label();
board[i].Parent = pictureBox1;
board[i].Location = new Point(x, y);
board[i].Name = "label" + i;
board[i].BackColor = Color.Black;
//set size of labels
board[i].Size = new Size(30, 30);
//initialize click event handler
this.board[i].Click += new System.EventHandler(this.labelClick);
}
private void labelClick (object sender, EventArgs e)
{
foreach (Label i in board)
{
if (iteration % 2 == 0)
{
i.BackColor = Color.Black;
iteration++;
}
else if(iteration % 2 == 1)
{
i.BackColor = Color.White;
iteration++;
}
}
}
There are a few ways you can handle this. One way is to wire each Labels Click event up to the same event:
this.label1.Click += new System.EventHandler(this.label_Click);
this.label2.Click += new System.EventHandler(this.label_Click);
this.label3.Click += new System.EventHandler(this.label_Click);
In the label_Click event you can set the BackColor of each label OR just the one you clicked on.
// This will set each label's BackColor to Red.
private void label_Click(object sender, EventArgs e)
{
foreach (Label label in labelArray)
{
label.BackColor = Color.Red;
}
}
// This will set just the clicked on Label's BackColor to Red.
private void label_Click(object sender, EventArgs e)
{
Label label = sender as Label;
if (label != null)
{
label.BackColor = Color.Red;
}
}
var labels = new[]
{
// labels here
};
foreach (var label in labels)
{
label.Click += (sender, args) =>
{
var lbl = sender as Label;
Debug.Assert(lbl != null);
lbl.BackColour = Colors.Pink;
};
}

Categories