How to add event on control created during runtime - c#

I want to create click event on buttons, (2 Buttons are creating during runtime)
I am using this to create buttons:
private void Form1_Load(object sender, EventArgs e)
{
for (int k = 0; k < 2; k++)
{
Button Btn = new Button();
Btn.Name = "btn" + k;
Btn.Location = new System.Drawing.Point(20 + (k *110), 60 + (20 * j) * 2);
Btn.Size = new System.Drawing.Size(90, 30);
if (k == 0)
Btn.Text = "Back";
else
Btn.Text = "Calculate";
this.Controls.Add(Btn);
}
}
Thanks in Advance.

Enhance your loop like this:
for (int k = 0; k < 2; k++)
{
Button Btn = new Button();
Btn.Name = "btn" + k;
Btn.Location = new System.Drawing.Point(20 + (k *110), 60 + (20 * j) * 2);
Btn.Size = new System.Drawing.Size(90, 30);
if (k == 0)
Btn.Text = "Back";
else
Btn.Text = "Calculate";
Btn.Click += button_Click; // <-- This is where it happens!
this.Controls.Add(Btn);
}
Then add the event handler:
private void button_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
if (btn.Name.Equals("..."))
{
}
else
{
}
}
Please note that within the event handler you need to decide which button has been pressed by looking at the Name property.

Simply use:
Btn.Click += button1_Click;
private void button1_Click(object sender, EventArgs e)
{
}

Like this
btn1.Click += new EventHandler(this.btn1_Click);

Btn.Click += Btn_Click;
void Btn_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}
in VS you can type Btn.Click += the press tab twice and it will generate the method for you.

Related

Cannot add a method to a button click event C# UWP

I have some problems making the HangMan game to work. Since i got my buttons, i had to make a method that displays the alphabet letters to user. So i have this Guessing method what i want to add to a button click event. So i get this red squiqqly line when i try to add a method to a button. The error is in HangMan_OnLoaded method. Thanks!
public void DisplayTheWord()
{
WrongGuesses = 0;
BitmapImage Hangman2 = new BitmapImage();
Uri URL = new Uri(BaseUri, images[WrongGuesses]);
Hangman2.UriSource = URL;
picture.Source = Hangman2;
string[] ReadWords = File.ReadAllLines("EnglishWords.txt");
int NextNumber = (new Random().Next(words.Length));
copyCurrent = "";
current = words[NextNumber];
for (int i = 0; i < ReadWords[NextNumber].Length; i++)
{
copyCurrent += "_" + " ";
}
CopiedWord.Text = copyCurrent;
}
private void Hangman_OnLoaded()
{
const int btnSize = 35;
var c = 0;
for (var i = 65; i <= 90; i++)
{
var btn = new Button();
btn.Content = (char)i;
btn.Width = btn.Height = btnSize;
var margin = btn.Margin;
margin.Left = c += 37;
btn.Margin = margin;
GridMain.Children.Add(btn);
btn.Click += Guessing();
}
}
private void Guessing(object sender, EventArgs e)
{
for (var i = 65; i <= 90; i++)
{
var btn = new Button();
btn = sender as Button;
btn.Content = (char) i;
var choice = btn.ToString();
if (copyCurrent.Contains(choice))
{
char[] temp = copyCurrent.ToCharArray();
char[] find = current.ToCharArray();
char guessChar = choice.ElementAt(0);
for (int index = 0; index < find.Length; index++)
{
if (find[index]== guessChar)
{
temp[index] = guessChar;
}
}
copyCurrent = new string(temp);
}
else
{
WrongGuesses++;
}
if (WrongGuesses < 6)
{
}
}
}
private void DisplayCopy()
{
CopiedWord.Text = "";
for (int index = 0; index < copyCurrent.Length; index++)
{
CopiedWord.Text += copyCurrent.Substring(index, 1);
CopiedWord.Text += " ";
}
}
You need to remove the brackets from the line:
btn.Click += Guessing();
so that it becomes:
btn.Click += Guessing;
#swatsonpicken said right. you need to remove the brackets from the line:
btn.Click += Guessing();
and replace with:
btn.Click += Guessing;
And one more thing you will need to correct that is the
private void Guessing(object sender, EventArgs e)
Write above line as below:
private void Guessing(object sender, RoutedEventArgs e)
Hope this will help. :)
I think:
The error is because Guessing is void and dont return nothing but yor're using Guessing like a method that return a event:
btn.Click += Guessing();
For dix that return a value event :)
Make sure your handler fits to Event you want to use:
private void Guessing(object sender, RoutedEventArgs e) {
//your handler code
}
btn.Click += Guessing;
Reason for that is, each event is expecting signature of delegate and defines parameters.

C# Button visible change when button cliked

i tried to do this(mine field) but i cant visible = false any button when im clicked that.
by the way this.visible = false is going to visible form -.-
private void Form1_Load(object sender, EventArgs e)
{
this.Size = new Size(541, 537);
for (int j = 24; j < ClientSize.Height; j += 25)
{
for (int i = 0; i < ClientSize.Width; i += 25)
{
Button btn = new Button();
btn.Width = 25;
btn.Height = 25;
btn.Location = new Point(i, j);
btn.Click += btn_Click;
Controls.Add(btn);
}
}
}
void btn_Click(object sender, EventArgs e)
{
//When i clicked anyone of them that comes be invisible,
}
thx for helping
The control that fired the event is stored in sender - cast it back to a Button.
void btn_Click(object sender, EventArgs e)
{
var button = (Button)sender;
button.Hide();
}
Alternatively, if that's all you're doing in the event, you could define it in a single line like this:
btn.Click += delegate { btn.Hide(); };

Adding Event Handler for Dynamically Created to window Form

I have a window form where I am creating a list of Checkboxes. The number of checkboxes created are based upon how many items are returned from the database. I've been able to create the checkboxes; however, I am not sure how to add event handlers for these checkboxes. For example, I'd like to add an OnCheckedChanged or CheckStateChanged event. How can I add these events? Also, I would appreciate any other suggestion. I am a total newbie to programming.
private void Form1_Load(object sender, EventArgs e)
{
CheckBoxes = new CheckBox[listGroup.Count()];
for (int i = 0; i < listGroup.Count(); i++)
{
CheckBoxes[i] = new CheckBox();
CheckBoxes[i].Text = listGroup.ElementAt(i).GroupName;
CheckBoxes[i].Name = "txt" + listGroup.ElementAt(i).GroupName.Replace(' ', '_');
CheckBoxes[i].CheckedChanged += new EventHandler(CheckBoxes[i]+"_CheckedChanged");
CheckBoxes[i].Width = 200;
if (i == 0)
{
CheckBoxes[i].Location = new System.Drawing.Point(5, 10);
}
else if (i == 1)
{
CheckBoxes[i].Location = new System.Drawing.Point(5, 40);
}
else if (i == 2)
{
CheckBoxes[i].Location = new System.Drawing.Point(5, 80);
}
this.Controls.Add(CheckBoxes[i]);
}
}
private void Form1_Load(object sender, EventArgs e)
{
//...
CheckBoxes[i].CheckedChanged += checkBoxes_CheckedChanged;
CheckBoxes[i].CheckStateChanged += checkBoxes_CheckStateChanged;
}
void checkBoxes_CheckedChanged(object sender, EventArgs e)
{ //do stuff when checked changed }
void checkBoxes_CheckStateChanged(object sender, EventArgs e)
{ //do stuff when check state changed }
Note: this will give identical event handling for all of your checkboxes.
If you want to do different things for different textboxes, you have to name the eventhandler differently and define that eventhandler.
A more efficient way to set the location of your checkboxes
for (int i = 0; i < listGroup.Count(); i++)
{
CheckBoxes[i] = new CheckBox();
CheckBoxes[i].Text = listGroup.ElementAt(i).GroupName;
CheckBoxes[i].Name = "txt" + listGroup.ElementAt(i).GroupName.Replace(' ', '_');
CheckBoxes[i].CheckedChanged += new EventHandler(CheckBoxes[i] + "_CheckedChanged");
CheckBoxes[i].Width = 200;
//set location based on index of i
CheckBoxes[i].Location = new System.Drawing.Point(5, 10 + (i * 30));
this.Controls.Add(CheckBoxes[i]);
}
private void LoadNewCheckboxes()
{
dynamic listGroupCount = 10;
List<System.Windows.Forms.CheckBox> CheckBoxes = new List<System.Windows.Forms.CheckBox>();
for (int i = 0; i <= listGroupCount - 1; i++)
{
System.Windows.Forms.CheckBox chkbox = new System.Windows.Forms.CheckBox();
chkbox.Text = i.ToString();
//listGroup.ElementAt(i).GroupName
chkbox.Name = "txt" + i.ToString();
//listGroup.ElementAt(i).GroupName.Replace(" "c, "_"c)
chkbox.CheckedChanged += new EventHandler(chkbox_CheckedChanged);
chkbox.CheckStateChanged += new EventHandler(chkbox_CheckStateChanged);
chkbox.Width = 200;
chkbox.AutoSize = true;
this.Controls.Add(chkbox);
CheckBoxes.Add(chkbox);
if (i == 0)
{
chkbox.Location = new System.Drawing.Point(5, 10);
}
else
{
chkbox.Location = new System.Drawing.Point(5, (CheckBoxes[i - 1].Top + CheckBoxes[i - 1].Height + 10));
}
}
}
private void chkbox_CheckedChanged(object sender, EventArgs e)
{
System.Windows.Forms.CheckBox chkbox = (System.Windows.Forms.CheckBox)sender;
if (chkbox != null)
{
//do somthing
Debug.WriteLine("chkbox_CheckedChanged");
Debug.WriteLine(chkbox.Text);
Debug.WriteLine(chkbox.Checked.ToString());
Debug.WriteLine(chkbox.Name.ToString());
}
}
private void chkbox_CheckStateChanged(object sender, EventArgs e)
{
System.Windows.Forms.CheckBox chkbox = (System.Windows.Forms.CheckBox)sender;
if (chkbox != null)
{
//do somthing
Debug.WriteLine("chkbox_CheckStateChanged");
Debug.WriteLine(chkbox.Text);
Debug.WriteLine(chkbox.Checked.ToString());
Debug.WriteLine(chkbox.Name.ToString());
}
}

Dynamically Created Combobox's SelectedIndexChanged Event

i'm designing a windows form application. In this app, user selects a number from a combobox, then depending on the number, some dynamic controls will be created(labels and comboboxes).
My problem is, i need to write some code on these dynamically created comboboxs' "selectedindexchanged" event. But i don't know how to create an event to dynamic combobox.
Here is my function:
FORM1.CS
public void getchildCntrl(Panel pnl,ComboBox cmbb)
{
for (int ix = pnl.Controls.Count - 1; ix >= 0; ix--)
if (pnl.Controls[ix].Name.Substring(0, 5) == "Child") pnl.Controls[ix].Dispose();
if (cmbb.SelectedIndex != 0)
{
Label[] childLabels = new Label[cmbb.SelectedIndex];
ComboBox[] txtTeamNames = new ComboBox[cmbb.SelectedIndex];
for (int i = 0; i < txtTeamNames.Length; i++)
{
//label create
var lbl = new Label();
childLabels[i] = lbl;
lbl.Name = "ChildLb" + i.ToString();
lbl.Text = (i + 1).ToString() + ". Çocuk-Yaş :";
lbl.Width = 80;
lbl.Location = new Point(cmbb.Location.X - 85, cmbb.Location.Y + 7 + ((i + 1) * 28));
lbl.Visible = true;
pnl.Controls.Add(lbl);
//combobox create
var cmb = new ComboBox();
txtTeamNames[i] = cmb;
cmb.Name = "Child" + i.ToString();
cmb.Location = new Point(cmbb.Location.X, cmbb.Location.Y + 5 + ((i + 1) * 28));
cmb.Width = 40;
cmb.DropDownStyle = ComboBoxStyle.DropDownList;
cmb.DataSource = ages.ToArray();
cmb.Visible = true;
pnl.Controls.Add(cmb);
}
}
}
You just register to the event like below...
cmb.SelectedIndexChanged += new System.EventHandler((object o, EventArgs e) =>
{
//Do something here
});
Or
cmb.SelectedIndexChanged += new System.EventHandler(cmb_SelectedValueChanged);
private void cmb_SelectedValueChanged(object sender, EventArgs e)
{
//Do something here.
}
You can hook up an event handler to the ComboBox like this:
cmd.SelectionChanged += new SelectionChangedEventHandler(GuiController_SelectionChanged);
void GuiController_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
throw new NotImplementedException();
}
Register event handler this way:
cmb.SelectedIndexChanged+=new EventHandler(cmb_SelectedIndexChanged);
Unregister this way:
cmb.SelectedIndexChanged-=new EventHandler(cmb_SelectedIndexChanged);
private void cmb_SelectedIndexChanged(object sender, System.EventArgs e)
{
//write your event code here
}
How to: Create Event Handlers at Run Time for Windows Forms
public void getchildCntrl(Panel pnl,ComboBox cmbb)
{
//// your code.....
//combobox create
var cmb = new ComboBox();
cmb.SelectedIndexChanged+=new EventHandler(cmb_SelectedIndexChanged);
// remaining code
cmb.Visible = true;
pnl.Controls.Add(cmb);
}
}
}
For specifying parameters - go through:
ComboBox.SelectedIndexChanged Event

How to assign click event

I have an array of button which is dynamically generated at run time. I have the function for button click in my code, but I can't find a way to set the button's click name in code. So,
what is the code equivalent for XAML:
<Button x:Name="btn1" Click="btn1_Click">
Or, what should I place for "????" in the following Code:
Button btn = new Button();
btn.Name = "btn1";
btn.???? = "btn1_Click";
Button btn = new Button();
btn.Name = "btn1";
btn.Click += btn1_Click;
private void btn1_Click(object sender, RoutedEventArgs e)
{
// do something
}
The following should do the trick:
btn.Click += btn1_Click;
// sample C#
public void populateButtons()
{
int xPos;
int yPos;
Random ranNum = new Random();
for (int i = 0; i < 50; i++)
{
Button foo = new Button();
Style buttonStyle = Window.Resources["CurvedButton"] as Style;
int sizeValue = ranNum.Next(50);
foo.Width = sizeValue;
foo.Height = sizeValue;
foo.Name = "button" + i;
xPos = ranNum.Next(300);
yPos = ranNum.Next(200);
foo.HorizontalAlignment = HorizontalAlignment.Left;
foo.VerticalAlignment = VerticalAlignment.Top;
foo.Margin = new Thickness(xPos, yPos, 0, 0);
foo.Style = buttonStyle;
foo.Click += new RoutedEventHandler(buttonClick);
LayoutRoot.Children.Add(foo);
}
}
private void buttonClick(object sender, EventArgs e)
{
//do something or...
Button clicked = (Button) sender;
MessageBox.Show("Button's name is: " + clicked.Name);
}
I don't think WPF supports what you are trying to achieve i.e. assigning method to a button using method's name or btn1.Click = "btn1_Click". You will have to use approach suggested in above answers i.e. register button click event with appropriate method
btn1.Click += btn1_Click;
You should place below line
btn.Click = btn.Click + btn1_Click;

Categories

Resources