i'm really new to C# and i been thinking why the label text changed when i set it in a different value without the help of a event handler?
Here's the my code :
class Main_Program : Form
{
Button btnAttack = new Button();
Label[] lblEnemyInfo = new Label[4];
public Main_Program()
{
btnAttack.Text = "ATTACK";
btnAttack.Location = new Point(350, 450);
btnAttack.Width = 150;
btnAttack.Height = 50;
btnAttack.FlatStyle = FlatStyle.Popup;
btnAttack.MouseClick += new MouseEventHandler(btnAttack_MouseClick);
for (short i = 0; i < 4; i++)
lblEnemyInfo[i] = new Label();
string enemyHealth = "Health : " + enemy.Health; //I'm going set the values on label 2
lblEnemyInfo[1].Text = enemyHealth;
lblEnemyInfo[1].Font = new Font("Segoi UI", 12, FontStyle.Italic);
lblEnemyInfo[1].Location = new Point(500, 50);
for (short i = 0; i < 4; i++)
Controls.Add(lblEnemyInfo[i]);
}
private void btnAttack_MouseClick(Object sender, EventArgs e)
{
short totalDamage = totalDamageDeal(enemy.Armor, player.Attack);
string log = "You Attack the enemy, you deal " + totalDamage + " damage";
enemy.Health -= totalDamage;
string result = "Health : " + enemy.Health;
lblEnemyInfo[1].Text = result;
lblEnemyInfo[1].TextChanged += new EventHandler(lblEnemyInfo_TextChanged); //The label's text changed even without the eventhandler
}
private void lblEnemyInfo_TextChanged (object sender, EventArgs e)
{
//i don't know what statements to put here
}
}
An EventHandler is used to execute code when an event happens. If you don't want anything to happen, then don't use an event handler.
In your case, lblEnemyInfo is a Label. It has a property called Label.Text (of type string). You can change this value to update the string that the Label displays. Using lblEnemyInfo[1].Text = "Health Down"; will make the corresponding Label display the value "Health Down" whether or not an event handler is associated with it.
You are setting an event handler for the Label with this code :
lblEnemyInfo[1].TextChanged += new EventHandler(lblEnemyInfo_TextChanged);
That means "whenever this Label's Text changes, call the function named lblEnemyInfo_TextChanged".
There is good documentation on event handling in this link (MSDN docs).
Related
In my code the buttons are made automatically and I need to save the information from the button in the click event. I am coding a ShopSystem in WindowsForms and when I click a button (should also work like clicking 3 times) it should stand in a text box at the next form but I just need help at coding the clickevent.
while (id < artikelAnzahl)
{
Button ArtikelID = new Button
{
Location = new Point(posX, posY),
Size = new Size(100, 75),
};
posX += 120;
double s = double.Parse(id.ToString()) / 5;
if (int.TryParse(s.ToString(), out int i))
{
posY += 100;
posX = 70;
}
this.Controls.Add(ArtikelID);
foreach (var p in xmlArtikelliste.Descendants("Artikel"))
{
if (int.Parse(p.Attribute("ID").Value) == id)
{
ArtikelID.Text = p.Element("Name").Value + " " +
p.Element("Preis").Value + "€ " +
p.Element("Anzahl").Value + "Stk. ";
}
}
id++;
}
Edit: Adding Click event delegate will not do the trick since the buttons are generated in a while loop and the event handler's action will always have the values from the last loop iteration.
So, you can achieve what you need with the following:
Button's Tag property for storing the data
You can store Article ID from xmlArtikelliste.Descendants("Artikel"), or the whole article if you will:
ArtikelID.Tag = p.Attribute("ID")
Event handler which will be added to the Button's Click event.
Sample code:
ArtikelID.Click += (sender, e) =>
{
if(sender is Button button)
{
// Pass button.Tag.ToString() as parameter when navigating to the other form;
}
};
You can read more about it on the official docs.
Complete code:
while (id < artikelAnzahl)
{
Button ArtikelID = new Button
{
Location = new Point(posX, posY),
Size = new Size(100, 75),
};
posX += 120;
double s = double.Parse(id.ToString()) / 5;
if (int.TryParse(s.ToString(), out int i))
{
posY += 100;
posX = 70;
}
this.Controls.Add(ArtikelID);
foreach (var p in xmlArtikelliste.Descendants("Artikel"))
{
if (int.Parse(p.Attribute("ID").Value) == id)
{
ArtikelID.Text = p.Element("Name").Value + " " +
p.Element("Preis").Value + "€ " +
p.Element("Anzahl").Value + "Stk. ";
ArtikelID.Tag = p.Attribute("ID");
}
}
ArtikelID.Click += (sender, e) =>
{
if (sender is Button button && button.Tag != null)
{
// Pass button.Tag.ToString() as parameter when navigating to the other form;
}
};
id++;
}
Edit 1:
(sender, e) is a standard delegate signature for event handlers which executes an Action.
Ideally, what you could do is create a list of buttons, add button template and bind the data received from xmlArtikell to it. You can have a look at the following introductory tutorial on data binding in Win Forms.
Edit 2: Added solution to store the data in Button's Tag property, so it can be utilized later in the Click event handler. Otherwise, the action will always have the last while loop iteration variables to work with.
I'm a computing foundation year student and am designing a basic e-commerce site for a project at uni and have run into a problem that has me banging my head against my desk
So..
I am dynamically creating a shopping basket using asp.net controls in the Page_Load method of the basket page based off what is in a session variable (type dictionary - the key is the product id and the value is the qty).
I can add items from the browse page which has more dynamically added controls based off whatever the user puts in the products table of the database, that works fine.
I can populate the basket with all the details but am struggling with a '-' and '+' button to alter the qty in the basket.
I can assign the event handler to run a method in a class that adds (or removes) 1 item at a time but the problem I face is if I place my code in Page_Load the function works but renders the controls before the event handler fires (so while the dictionary updates, it's not showing the new value - you have to refresh or add another and then you're always 1 behind)
If I place the code in PreRender the event handler doesnt fire.
This is my first ever project in ASP.NET so please go easy on me if I'm barking up the wrong tree with my methodology.
Any ideas or a nudge in the right direction would be gratefully received
Many thanks in advance
EDIT To add a bit more detail
//creating my button
Button tdQtyDownButton = new Button();
tdQtyDownButton.ID = "qtyDown"+ row["prod_id"]; tdQtyDownButton.Text = "-";
tdQtyDownButton.Click += delegate (object sender1, EventArgs e1) {
ShoppingBasket.AddItem((int)row["prod_id"]); };
tdQtyDown.Controls.Add(tdQtyDownButton);
//in seperate ShoppingBasket class file
public static void AddItem(int prod_id)
{
if (HttpContext.Current.Session["basket"] != null)
{
if(!((Dictionary<int, int>)HttpContext.Current.Session["basket"]).ContainsKey(prod_id))
{
((Dictionary<int, int>)HttpContext.Current.Session["basket"]).Add(prod_id, 1);
}
else
{
int currentQty = 0;
((Dictionary<int, int>)HttpContext.Current.Session["basket"]).TryGetValue(prod_id, out currentQty);
((Dictionary<int, int>)HttpContext.Current.Session["basket"]).Remove(prod_id);
((Dictionary<int, int>)HttpContext.Current.Session["basket"]).Add(prod_id, currentQty + 1);
}
}
else
{
CreateBasket();
AddItem( prod_id);
}
}
As i said, it sort of works - I think it's a just a lifecycle issue and probably needs a wholly fresh approach
Assuming you want to add a Button dynamically and handle it's click event :
Button button1 = new Button();
button1.Text = "dynamic button";
button1.Left = 10; button1.Top = 10;
textBox1.Click += new EventHandler(btn_click);
this.Controls.Add(button1);
private void btn_click()
{
}
Update : From your comment,it seems like that you want to refresh your page without reloading it...For that,your easiest approach will be SignalR or you can use the UpdatePanel Control
For Windows Form Application
public partial class Form1 : Form
{
int i = 1;
int j = 1;
int rbCount = 0;
public Form1()
{
InitializeComponent();
}
private void buttonAddRadio_Click(object sender, EventArgs e)
{
RadioButton rb = new RadioButton();
rb.Name = "Radio Button" + i.ToString();
rb.Text = "Radio Button" + i;
rb.Left = 8;
rb.Top = 15 + (rbCount * 27);
rb.AutoSize = true;
rb.Click += new EventHandler(radio_click);
groupBox1.Controls.Add(rb);
i++;
rbCount++;
}
void radio_click(object sender, EventArgs e)
{
MessageBox.Show(((RadioButton)sender).Text);
}
private void buttonAddCheck_Click(object sender, EventArgs e)
{
CheckBox cb = new CheckBox();
cb.Name = "CheckBox" + j.ToString();
cb.Text = "CheckBox" + j;
cb.Left = 8;
cb.Top = 15 + (rbCount * 27);
cb.AutoSize = true;
cb.Click += new EventHandler(checkbox_checked);
groupBox1.Controls.Add(cb);
j++;
rbCount++;
}
void checkbox_checked(object sender, EventArgs e)
{
MessageBox.Show(((CheckBox)sender).Text);
}
}
For ASP.NET Web Application
string[] myArray = new string[] { "Alex", "Bob", "John", "Srinivas", "Zamal", "Rahul" }
foreach (string item in myArray)
{
HyperLink myHyp = new HyperLink();
myHyp.Text = Suspect;
myHyp.NavigateUrl = "User Details.aspx?name=" + HttpUtility.UrlEncode(item));
myPanel.Controls.Add(new LiteralControl("<ul>"));
myPanel.Controls.Add(new LiteralControl("<li>"));
myPanel.Controls.Add(hpSuspect);
myPanel.Controls.Add(new LiteralControl("</li>"));
myPanel.Controls.Add(new LiteralControl("</ul>"));
}
N.B. LiteralControl is used for adding general HTML controls.
I have created a set of button and attach Click event and GotFocus event to them.
for (int i = 0; i < NumberOfQuestion; i++)
{
RadButton button = new RadButton();
// radButton1
//
button.Anchor = AnchorStyles.None;
button.Font = new Font("Segoe UI", 8.25F, FontStyle.Bold);
button.Location = new Point(65 * i + 15, 10);
button.Name = "btn_cauhoi" + (i + 1);
button.Size = new Size(60, 35);
button.TabIndex = 1 + i;
button.Text = "Câu " + (i + 1);
button.Tag = (i + 1);
button.Click += Button_Click;
button.GotFocus += Button_Click; ;
//
panel_nut_cauhoi.Controls.Add(button);
}
private void Button_Click(object sender, EventArgs e)
{
var button = (RadButton)sender;
var index = (int)button.Tag;
MessageBox.Show(index.ToString());
}
It triggers Click event correctly but with GotFocus event it trigger repeatly.
Somebody helps me, please.
Thanks in advances.
When you click ok on message box it loose focus and get focus again.
So if you delete MessageBox.Show() you will see its gonna trigger only one time, so you can test code like below, you will see the name of the button as btn_cauhoi1 or btn_cauhoi2 or btn_cauhoi3 up to which button you do click, it means its gonna trigger only one time.
var button = (RadButton)sender;
var index = (int)button.Tag;
//MessageBox.Show(index.ToString());
this.Text = button.Name;
I have an array of buttons, like this:
int x = 0, y = 0;
butt2 = new Button[100];
for (int i = 0; i < 100; i++)
{
butt2[i] = new Button();
int names = i;
butt2[i].Name = "b2" + names.ToString();
butt2[i].Location = new Point(525 + (x * 31), 70 + (y * 21));
butt2[i].Visible = true;
butt2[i].Size = new Size(30, 20);
butt2[i].Click += new EventHandler(butt2_2_Click); //problem lies here (1)
this.Controls.Add(butt2[i]);
}
private void butt2_2_Click(object sender, EventArgs e)
{
// want code here
}
I want to change the back color of the button when clicked. I was thinking of passing i to be able to do this:
butt2[i].BackColor = Color.Green;
This should do the trick:
private void butt2_2_Click(object sender, EventArgs e)
{
Button pushedBtn = sender as Button;
if(pushedBtn != null)
{
pushedBtn.BackColor = Color.Green;
}
}
And this holds for most UI events, the 'object sender' parameter refers to the control that 'sent'/'fired' the event.
To learn more about C# event handling, I would start here.
Also, here is a SO question about GUI event handling, answered nicely by Juliet (accepted answer).
Hope this helps.
I was wondering how to go about doing something such as this:
I need to create a Form with a specific number of buttons based on an integer value representing the number of buttons needed, then give them their own specific names so that each can have their own unique event handlers.
A real example I can think of doing this would be the Windows log-in screen, where the number of controls created is based on the number of users and whether there is a Guest account or not. How do you think that they programmed that?
Thank you.
for (int i = 0; i < 5; i++)
{
Button newButton = new Button();
newButton.Name = "button" + i.ToString();
newButton.Text = "Button #" + i.ToString();
newButton.Location = new Point(32, i * 32);
newButton.Click += new EventHandler(button1_Click);
this.Controls.Add(newButton);
}
private void button1_Click(object sender, EventArgs e)
{
if (((Button)sender).Name == "button0")
MessageBox.Show("Button 0");
else if (((Button)sender).Name == "button1")
MessageBox.Show("Button 1");
}
Somehow you have to define the names of all the buttons. I would suggest you to create a new string array and write the button names inside, and then use them in buttons creation loop:
//do the same length as the for loop below:
string[] buttonNames = { "button1", "button2", "button3", "button4", "button5" };
for (int i = 0; i < buttonNames.Lenght; i++)
{
Button newButton = new Button();
newButton.Name = "button" + i.ToString();
newButton.Text = buttonNames[i]; //each button will now get its own name from array
newButton.Location = new Point(32, i * 32);
newbutton.Size = new Size(25,100); //maybe you can set different sizes too (especially for X axes)
newButton.Click += new EventHandler(buttons_Click);
this.Controls.Add(newButton);
}
private void buttons_Click(object sender, EventArgs e)
{
Button btn = sender as Button
MessageBox.Show("You clicked button: " + btn.Text + ".");
}