Eventhandler for multiple generated buttons C# - c#

I have generated multiple buttons when I click on btnStart and I'd like to use booleans for each button to become true when it gets clicked so I can check the clicked buttons later on but I only know how to use the same event for every button
This is what I use to create the buttons (I left some unnecessary things out)
for (int i = 0; i < 5; i++) //I use this to horizontally generate buttons
{
for (int j = 0; j < 4; j++) //vertically generate buttons
{
Button btnNew = new Button();
btnNew.Name = "btnFlag" + i;
btnNew.Click += new EventHandler(btnNew_Click);
Controls.Add(btnNew);
aButtons.Add(btnNew); //this is a list I use to set random bgImages
}
}
Now when I click on btnNew it would do all the code set for the event btnNew_Click but I can't use btnFlag1_Click because it doesn't exist, does anyone know a way to create booleans for every buttons and set one to true when a specific button is being clicked
Like: when btnFlag1 gets clicked, turn boolean btn1 to true
and so on ..
Thank you in advance

When you are looping in your for statement you are assigning same event to all your methods.But the sender paramater of your method contains the reference of the button which is calling the specific event.
you can bind all the buttons to same event
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 4; j++)
{
Button btnNew = new Button();
btnNew.Name = "btnFlag" + i;
btnNew.Click += new EventHandler(btnNew_Click);
}
}
Then inside the button click new event you can select your specific sender and perform specific actions
public void btnNew_Click(object sender, ButtonEventArgs e)
{
Button b = sender as Button;
if( b.Name == "btnFlag0" )
{
//logic for your 1st btn
}
//.... repeat the same logic for others
}

You can use the sender argument in the event handler, which in fact is the specific Button which was clicked:
private void btnNew_Click(Object sender, EventArgs e)
{
Button btn = sender as Button;
string name = btn.Name;
}

Related

How to deselect all controls in a form?

I have dynamically created a list of buttons and set it to the form. After clicking one of them, the very next button to it will appear as selected.
Is it possible to deselect all controls dynamically created in a form? Particularly, can I, somehow, deselect that button after clicking the one before it?
private void GenerateButton()
{
for (int i = 1; i <= 15; ++i)
{
for (int j = 1; j <= 25; ++j)
{
Button button = new Button();
button.Location = p;
button.Size = size;
button.BackColor = Color.RoyalBlue;
button.Padding = pad;
button.Click += new EventHandler(button_Click);
this.Controls.Add(button);
p.X += 23;
}
p.Y += 23;
p.X = 0;
}
}
protected void button_Click(object sender, EventArgs e)
{
Button but = sender as Button;
but.Enabled = false;
but.BackColor = Color.LightGray;
}
You might try this method, which will select the next button in the form, after clicking on a button. You need to attach this button event handler to all your buttons. The order of buttons is determined by their order in the form Controls list. If you want a specific order, you will need to use LINQ to sort Controls by their TabOrder property and ensure your TabOrder is set properly
private void button_Click(object sender, EventArgs e)
{
var btn = (Control)sender;
btn.Enabled = false;
btn.BackColor = Color.LightGray;
// Where is this button in the form?
var indexOfThisButton = this.Controls.IndexOf(btn);
// Find next button index
for (int i = indexOfThisButton+1; i < this.Controls.Count; i ++)
{
// If it's a button, select it
if (this.Controls[i] is Button)
{
this.Controls[i].Select();
return;
}
}
// If we got down here we have got to the end of the controls list, start again
for (int i = 0; i < this.Controls.Count; i++)
{
// If it's a button, select it
if (this.Controls[i] is Button)
{
this.Controls[i].Select();
return;
}
}
}

What event is triggered when the mouse pointer enters a MenuflyoutSubItem element?

PointerEntered is triggered when the mouse pointer enters a MenuFlyoutItem, but not when it enters a MenuFlyoutSubItem. What event is triggered when the mouse pointer enters a MenuflyoutSubItem element? I want to capture the text property of the MenuflyoutSubItem element in an event handler when the mouse pointer enters it. (The reason I can't rely on the tapped event is because even just hovering over the MenuFlyoutSubItem opens its contained menu items.) Here is the code:
public DynamicMenuTestPage()
{
InitializeComponent();
for (int i = 0; i < 5; i++)
{
MenuFlyoutSubItem myItem = new MenuFlyoutSubItem();
myItem.Text = "Item" + i;
myItem.PointerEntered += MyItem_PointerEntered;
MyMenu.Items.Add(myItem);
for (int j = 0; j < 4; j++)
{
MenuFlyoutItem mySubItem = new MenuFlyoutItem();
mySubItem.Text = "SubItem" + j;
mySubItem.PointerEntered += mySubItem_PointerEntered;
myItem.Items.Add(mySubItem);
}
}
}
private void MyItem_PointerEntered(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e)
{
// This does not work. It is not triggered when the mouse pointer enters the menu flyout subitem.
MenuFlyoutSubItem test = sender as MenuFlyoutSubItem;
var menuFlyoutSubItemText = test.Text;
}
private void mySubItem_PointerEntered(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e)
{ //This works. It is triggered when the mouse pointer enters the menu flyout item.
MenuFlyoutItem test = sender as MenuFlyoutItem;
var menuFlyoutItemText = test.Text;
}
Here is a screenshot of the menu. When I hover over Item0, circled in red, the submenu opens. What event will enable me to capture the text, "Item0"?
It seems the MenuFlyoutSubItem doesn't fire the PointerEntered RoutedEvents, you can wire an event handler for this RoutedEvents.
myItem.AddHandler(PointerEnteredEvent, new PointerEventHandler(PointEnterHandler), true);
So your code will be like this:
public MainPage()
{
this.InitializeComponent();
for (int i = 0; i < 5; i++)
{
MenuFlyoutSubItem myItem = new MenuFlyoutSubItem();
myItem.Text = "Item" + i;
myItem.AddHandler(PointerEnteredEvent, new PointerEventHandler(PointEnterHandler), true);
MyMenu.Items.Add(myItem);
for (int j = 0; j < 4; j++)
{
MenuFlyoutItem mySubItem = new MenuFlyoutItem();
mySubItem.Text = "SubItem" + j;
mySubItem.PointerEntered += mySubItem_PointerEntered;
myItem.Items.Add(mySubItem);
}
}
}
private void PointEnterHandler(object sender, PointerRoutedEventArgs e)
{
MenuFlyoutSubItem test = sender as MenuFlyoutSubItem;
var menuFlyoutSubItemText = test.Text;
}
private void mySubItem_PointerEntered(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e)
{ //This works. It is triggered when the mouse pointer enters the menu flyout item.
MenuFlyoutItem test = sender as MenuFlyoutItem;
var menuFlyoutItemText = test.Text;
}

Dynamically create buttons in c# by user at runtime

How to create buttons dynamically after user input in C# (Visual Studio).
There is a text-box to enter how many buttons user wants?
Then my target is to create buttons below the input field as the user wants
then how can I get id's of that buttons?
private void button1_Click(object sender, EventArgs e)
{
List<Button> buttons = new List<Button>();
for (int i = 0; i < n; i++)
{
this.Controls.Add(buttons[i]);
}
}
Here I first added an event handler to the textbox, which is called whenever the text value is changed. The value is converted to the int value and then is used in a for loop statement. You can set your button's potion to the desired value using location property. Using tag or name property you can assign a unique value to your buttons. I hope the code helps.
Look at the code below :
private void Form1_Load(object sender, EventArgs e)
{
textBox1.TextChanged += textBox1_TextChanged;
}
void textBox1_TextChanged(object sender, EventArgs e)
{
var txtBox = sender as TextBox;
if (txtBox == null) return;
var count = Convert.ToInt16(txtBox.Text);
//
var xPosition = 0;
for (var i = 1; i <= count; i++)
{
var button = new Button
{
Tag = string.Format("Btn{0}", i),
Text = string.Format("Button{0}",i),
Location = new Point(xPosition, 0)
};
xPosition = xPosition + 100;
Controls.Add(button);
}
When you are creating Control(in your case Buttons) you can give them Name property. It will be very good if that name will be unique.
var btn = new Button();
btn.Name = "MyBtn";
btn.Text = "Our Button";
this.Controls.Add(btn);
For creation of N buttons you just need to put this in a Loop with N iterations and set btn.Name to something like "Name"+SomeNumber.
To set the Position of the Buttons to below the input you should set btn.Left and btn.Top to the corresponding coordinates.
Then when you need to work with generated Control/Button you can do search by that Name in the following way:
var btn = (Button)this.Controls.Find("MyBtn", true).First();
and do whatever you want with that Control/Button.
But in this case there is some danger as I am not checking if there was found any control with that name. If you write incorrect Name this will throw exception on .First().

How to make submit button appear after all text boxes are full?

I'm making a game with 6 dynamic buttons as "btn" at the top row and other 6 "lamp buttons" on a buttom row.
Player clicks on a top row button and text displayed in a bottom row button after clicking on it.
As soon as all the lamp buttons are full with text, I want a submit buttom to appear.
I tried to make for and foreach for my lamp buttons and it didn't help. Plese help!
here is a code:
public partial class Game : System.Web.UI.Page
{
protected void Page_Init(object sender, EventArgs e)
{
for (int i = 0; i < 6; i++)
{
Button btnLamp = new Button();
btnLamp.ID = "btnLamp" + i.ToString();
btnLamp.Click += btnLamp_Click;
this.Panel1.Controls.Add(btnLamp);
}
LiteralControl ltBreak = new LiteralControl();
ltBreak.Text = "<br/><br/>";
Panel1.Controls.Add(ltBreak);
Panel1.DataBind();
for (int i = 0; i < 6; i++)
{
Button btn = new Button();
btn.ID = "btn" + i.ToString();
btn.Text = "btn" + i.ToString();
btn.Click += btn_Click;
this.Panel2.Controls.Add(btn);
}
Panel2.DataBind();
}
void btn_Click(object sender, EventArgs e)
{
Button clickedbutton = (Button)sender;
string btn_cliked = clickedbutton.ID;
for (int i = 0; i <5 ; i++)
{
((Button)FindControl(("btn" + i.ToString()))).BackColor = System.Drawing.Color.LightSteelBlue;
}
clickedbutton.BackColor = System.Drawing.Color.Beige;
Session["clickedbutton"] = clickedbutton;
}
void btnLamp_Click(object sender, EventArgs e)
{
Button clickedbutton = (Button)sender;
string btnLamp_cliked = clickedbutton.ID;
((Button)FindControl(((Button)Session["clickedbutton"]).ID)).Enabled = false;
for (int i = 0; i < 5; i++)
{
if (((Button)Session["clickedbutton"]).Text.ToString() == ((Button)FindControl("btnLamp" + i)).Text)
{
((Button)FindControl("btnLamp" + i)).Text = "";
}
}
clickedbutton.Text = ((Button)Session["clickedbutton"]).Text.ToString();
}
This sort of stuff is best handled client side in javascript.
Attach a handler to the onchange event of your inputs and figure out inside it if
all inputs have value. Then show your button on page (should be present but hidden - display:none).
If none of the above makes any sense i suggest to do some research on web programming. Figure out the purpose of server code (C# in your case) versus html and javascript. Then come back with questions if needed

Click event for dynamically created array of buttons

In my application i have array of buttons created dynamically.I am trying to raise an onclick event for those buttons and change the text of the button which i click.I tried the below code for this but its not working.How can i do this?.Any suggesions?
Code:
for (int i = 0; i < 5; i++)
{
lbl = new Button[5];
lbl[i] = new Button();
lbl[i].Text = "hi";
lbl[i].Width = 30;
lbl[i].Click += new EventHandler(lbl_click);
//lbl[i].CssClass = "label";
div1.Controls.Add(lbl[i]);
}
Click Event:
protected void lbl_click(object sender, EventArgs e)
{
Button[] lbl = sender as button[];
lbl[i].Text = "clicked";
}
You are recreating the array of buttons in your event handler, but this array is not populated with the buttons created before. It is empty and will give you a null reference exception if you try to use an element of this array (null.Text, it will never work).
The sender object instead, represent the button that the user has clicked.
protected void lbl_click(object sender, EventArgs e)
{
Button lbl = sender as Button;
lbl.Text = "clicked";
}
Also, if you need to know which specific button has been clicked then I suggest you to add something to differentiate between them at creation time:
For example use the name property:
Button[] lbl = new Button[5];
for(int i = 0; i< 5; i++)
{
....
lbl[i].Name = "Button_" + i.ToString();
....
}
Notice that I have moved the array declaration and initialization outside the loop that create every single element of the array (the actual button).

Categories

Resources