WinForms button click event not firing - c#

I don't get any errors from Visual Studio so I assumed that the code was right. When I run the code, I press the button (button1), but nothing happens.
private void button1_Click(object sender, EventArgs e)
{
int a = 0;
int b = 1;
int c = 1;
listBox1.Text += a.ToString();
listBox1.Text += b.ToString();
for (int i = 0; i < 20; i++)
{
c = b;
b = a + b;
a = c;
listBox1.Text += b.ToString();
}
}

Listbox's Text property won't work in this case, since it is used only to set or get the selected item in a listbox, add to the itemsource on each number, then it will work
private void button1_Click(object sender, EventArgs e)
{
int a = 0;
int b = 1;
int c = 1;
StringBuilder finalstring = new StringBuilder();
listBox1.Text += a.ToString();
listBox1.Text += b.ToString();
for (int i = 0; i < 20; i++)
{
c = b;
b = a + b;
a = c;
listBox1.Items.Add(b);
}
}

Does button have button1_Click registered as an event?
You can do it via your code by adding button1.Click += button1_Click, or double clicking it in your form designer.
If this still does not work, put a breakpoint on the code to see if it is executed.

Related

Retrieving values from dynamically created controls Label in asp .net

I have created Label controls dynamically on button click:
protected void createDynamicLabels_Click(object sender, EventArgs e)
{
int n = 5;
for (int i = 0; i < n; i++)
{
Label MyLabel = new Label();
MyLabel.ID = "lb" + i.ToString();
MyLabel.Text = "Labell: " + i.ToString();
MyLabel.Style["Clear"] = "Both";
MyLabel.Style["Float"] = "Left";
MyLabel.Style["margin-left"] = "100px";
Panel1.Controls.Add(MyLabel);
}
}
When I tried to read back fro another button I see Label Control returned null
Label str = (Label)Panel1.FindControl("lb" + i.ToString());
not sure what went wrong here
protected void bReadDynValue_Click(object sender, EventArgs e)
{
int n = 5;
for (int i = 0; i < n; i++)
{
Label str = (Label)Panel1.FindControl("lb" + i.ToString());
lbGetText.Text = str.Text;
}
}
this is the issue of every time page load event. ASP.net fire every time page load event when any button is click.
suppose in this example..
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
createDynamicLabels();
}
private void createDynamicLabels()
{
int n = 5;
for (int i = 0; i < n; i++)
{
Label MyLabel = new Label();
MyLabel.ID = "lb" + i.ToString();
MyLabel.Text = "Labell: " + i.ToString();
MyLabel.Style["Clear"] = "Both";
MyLabel.Style["Float"] = "Left";
MyLabel.Style["margin-left"] = "100px";
Panel1.Controls.Add(MyLabel);
}
}
protected void bReadDynValue_Click(object sender, EventArgs e)
{
int n = 5;
for (int i = 0; i < n; i++)
{
Label str = (Label)Panel1.FindControl("lb" + i.ToString());
lbGetText.Text = str.Text;
}
}
when Button trigger Page doesn't have any label because it is made on runtime. and Page doesn't find particular label. if you tried above code it is run properly.
protected void Page_Load(object sender, EventArgs e)
{
createDynamicLabels();
}
private void createDynamicLabels()
{
int n = 5;
for (int i = 0; i < n; i++)
{
Label MyLabel = new Label();
MyLabel.ID = "lb" + i.ToString();
MyLabel.Text = "Labell: " + i.ToString();
MyLabel.Style["Clear"] = "Both";
MyLabel.Style["Float"] = "Left";
MyLabel.Style["margin-left"] = "100px";
Panel1.Controls.Add(MyLabel);
}
}
protected void bReadDynValue_Click(object sender, EventArgs e)
{
int n = 5;
for (int i = 0; i < n; i++)
{
Label str = (Label)Panel1.FindControl("lb" + i.ToString());
lbGetText.Text = str.Text;
}
}
in this Example code find label every time because every time it can make labels for this page.
Dynamically created labels exists only until the next postback occurs. When you click on another button to retrieve their values a postback occurs and values become null.
For saving labels state after postback you have to use some hidden field.
If the text / value of the labes does not change it is enough to generate them on every postback (as mck already mentioned). If you need to retrieve changes made on the client side, you should create the controls in the OnInit event instead of the PageLoad and use inputs / texboxes instead of labels.
Another option (which I would recommend) would be to use a asp:Repeater to generate the Labels.

Click event for a Button Array

I have a Button array in C# WFA and I want to create an event for a click of any button in the array.
How can I do it?
And how to know which location in the array it is?
I know sender is the button itself
You can use a for loop that closes over a variable containing the current index:
for(int i = 0; i < buttons.Length; i++)
{
//it's important to have this; closing over the loop variable would be bad
int index = i;
buttons[i].Click += (sender, args) => SomeMethod(buttons[index], index);
}
You can add the event handler to each button in a for loop.
Inside the handler, you can call array.IndexOf((Button)sender).
try this
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Button[] myButtons = new Button[10];
private void Form1_Load(object sender, EventArgs e)
{
for(int i = 0; i < myButtons.Length; i++)
{
int index = i;
this.myButtons[i] = new Button();
this.myButtons[i].Location = new System.Drawing.Point(((i + 1) * 70), 100 + ((i + 10) * 5));
this.myButtons[i].Name = "button" + (index + 1);
this.myButtons[i].Size = new System.Drawing.Size(70, 23);
this.myButtons[i].TabIndex = i;
this.myButtons[i].Text = "button" + (index + 1);
this.myButtons[i].UseVisualStyleBackColor = true;
this.myButtons[i].Visible = true;
myButtons[i].Click += (sender1, ex) => this.Display(index+1);
this.Controls.Add(myButtons[i]);
}
}
public void Display(int i)
{
MessageBox.Show("Button No " + i);
}
}
}

Button Click Frequency Array

I need to make a ListBox that displays how often a Button is clicked.
The user chooses how many buttons are available to click. Here is what I've tried:
int clicked;
clicked = int.Parse(((Button)(sender)).Text);
freq_array[clicked]++;
for (int i = 0; i < freq_array[clicked]; i++)
lstFrequencies.Items[clicked] = clicked + "\t\t" + freq_array[clicked];
freq_array uses the 'clicked' variable to add to the frequency that button has been clicked. Or, it's supposed to.
When I debug it, 'clicked' always comes out to 0. I want 'clicked' to equal the text value of the button that's clicked. When I try to run the program, I get an error saying "Input string was not in correct format."
Edit:
I was able to fix my program with help from you guys. I realized I didn't show enough of my code to be clear enough, and I apologize for that. I had to add some things and move things around and got it soon enough. Thank you all.
Here is the code just for those who may need help in the future:
public partial class Form1 : Form
{
int[] freq_array = new int[11];
int[] numList = new int[11];
int oBase = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
invisiblity();
}
private void invisiblity()
{
foreach (Control ctrl in this.Controls)
{
if (ctrl is Button)
if (Char.IsDigit(ctrl.Text[0]))
ctrl.Visible = false;
}
}
private void btnSetBase_Click(object sender, EventArgs e)
{
Form2 frmDialog = new Form2();
frmDialog.ShowDialog(this);
if (frmDialog.DialogResult == DialogResult.OK)
{
oBase = frmDialog.Base;
//lblOutDigits.Text = oBase.ToString();
for (int i = 0; i < oBase; i++)
{
numList[i] = i;
}
}
ShowBaseButtons(oBase);
}
private void ShowBaseButtons(int last_digit)
{
invisiblity();
foreach (Control ctrl in this.Controls)
{
if (ctrl is Button)
if (Char.IsDigit(ctrl.Text[0]))
if (int.Parse(ctrl.Text) <= last_digit - 1)
ctrl.Visible = true;
}
}
private void btnN_Click(object sender, EventArgs e)
{
lblOutDigits.Text += ((Button)(sender)).Text;
int clicked = int.Parse(((Button)(sender)).Text);
freq_array[clicked]++;
}
private void btnShowFreq_Click(object sender, EventArgs e)
{
lstFrequencies.Items.Clear();
for (int i = 0; i < oBase; i++)
lstFrequencies.Items.Add(numList[i] + " \t\t\t" + freq_array[i]);
}
Your code should work as long as your Button Text is actually just a number. Since what you are trying to do is create an index, what I usually do is use the Tag Property of the control, set it to the Index I want in the designer and then cast that to an Int.
i.e.
if (int.TryParse(((Button)sender).Tag.ToString(), out clicked))
freq_array[clicked]++;
I believe what is happening is that you are not initializing your ListBox, This example Code does work using your initial method. Just create a new Form and paste it in and test.
public partial class Form1 : Form
{
ListBox lstFrequencies = new ListBox();
int[] freq_array = new int[10];
public Form1()
{
InitializeComponent();
Size = new Size(400, 400);
lstFrequencies.Location = new Point(150, 0);
lstFrequencies.Size = new Size(150, 200);
Controls.Add(lstFrequencies);
int top = 0;
for (int i = 0; i < 10; i++)
{
Button btn = new Button();
btn.Size = new Size(70, 30);
btn.Location = new Point(5, top);
Controls.Add(btn);
top += 35;
btn.Tag = i;
btn.Text = i.ToString();
btn.Click += new EventHandler(btn_Click);
lstFrequencies.Items.Add(i.ToString());
}
}
void btn_Click(object sender, EventArgs e)
{
int clicked;
clicked = int.Parse(((Button)(sender)).Text);
freq_array[clicked]++;
lstFrequencies.Items[clicked] = clicked + "\t\t" + freq_array[clicked]; //Cleaned up you do not need to iterate your list
// Using my example code
//if (int.TryParse(((Button)sender).Tag.ToString(), out clicked))
//{
// freq_array[clicked]++;
// lstFrequencies.Items[clicked] = clicked + "\t\t" + freq_array[clicked];
//}
}
}
Your code always comes out to 0 because you never assign last clicked value to button text. Try this code:
int clicked = 0;
private void button1_Click(object sender, EventArgs e)
{
clicked = Convert.ToInt32(((Button)sender).Text);
lstFrequencies.Items.Add(((Button)sender).Name + " " + ++clicked);
button1.Text = clicked.ToString(); // you lose this line
}
EDIT: Counter from variable member
int clicked = 0;
private void button1_Click(object sender, EventArgs e)
{
// if you want to display button name, change .Text to .Name
lstFrequencies.Items.Add(((Button)sender).Text + " " + ++clicked);
}

Add Arrays of C# button Click in code in Run Time

To create Button and its click event in run time I use:
Button b = new Button();
b.Name = "btn1";
b.Click += btn1_Click;
But now I have an array of Buttons to create in run time; how to set each button's event - I cannot interpolate because it's not a string.
Button[] b = new Button(Count);
for (int i=0; i < Count; i++)
{
b[i] = new Button();
b[i].Name = "btn" + i;
b[i].Click += ??????
}
what should I do for "?????"
Option 1:
You can pass an lambda function, and create the handler based on the buttons index in the array like this:
for (int i=0; i < Count; i++)
{
b[i] = new Button();
b[i].Name = "btn" + i;
b[i].Click += (sender, args) =>
{
// your code
}
}
Option 2:
You can pass an anonymus delegate:
b[i].Click += delegate (sender, args) {
// your code
};
Option 3:
You can specify a handler function:
b[i].Click += YourHandlerFunction
// ....
// The handler signature also has to have the correct signature
void YourHandlerFunction(object sender, ButtonEventArgs args)
{
// your code
}
You can bind all buttons to the same event, so put the line like b[i].Click += button_Click;.
Then inside the button_Click event you can differentiate between the buttons, and take the proper actions.
For example:
public void button_Click(object sender, ButtonEventArgs e)
{
if( sender == b[0] )
{
//do what is appropriate for the first button
}
...
}
It depends on what you want to do! If you want to have the same method called for all clicks, do this:
Button[] b = new Button[Count];
for (int i=0; i < Count; i++)
{
b[i] = new Button();
b[i].Name = "btn" + i;
b[i].Click += OnClick
}
private void OnClick(object sender, RoutedEventArgs e)
{
// do something
}
If you want to do something different for each button, e.g. depending on the index, you can do something like this:
Button[] b = new Button[Count];
for (int i=0; i < Count; i++)
{
b[i] = new Button();
b[i].Name = "btn" + i;
b[i].Click += (s, e) => { /*do something*/ };
}

Changing properties of the sender object without knowing its name

I am trying to change the BackColor of a PictureBox in a grid. The PictureBox is part of an array and the array has a chared event handler. I am having difficulty changing different PictureBox's depending on which one is clicked.
This is what I have so far:
private PictureBox[,] GameGrid = new PictureBox[20, 20];
public frmGame()
{
int x = 10;
int y = 10;
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
GameGrid[i, j] = new System.Windows.Forms.PictureBox();
setUpPicBox(x, y, i, j);
x += 11;
}
y += 11;
x = 10;
}
InitializeComponent();
}
public void setUpPicBox(int x, int y, int i, int j)
{
this.GameGrid[i, j].Location = new System.Drawing.Point(x, y);
this.GameGrid[i, j].Size = new System.Drawing.Size(10, 10);
this.GameGrid[i, j].BackColor = Color.Black;
this.GameGrid[i, j].Name = "btnGrid" + i + "-" + j;
this.GameGrid[i, j].Visible = true;
this.GameGrid[i, j].CreateGraphics();
this.GameGrid[i, j].Click += new System.EventHandler(this.picturebox_Click);
this.Controls.Add(GameGrid[i, j]);
}
private void picturebox_Click(object sender, EventArgs e)
{
}</code>
Any help would be appreciated
The event handler's sender parameter is the instance that raised the event. Here it is the PictureBox instance that the user has clicked. If you want to change its BackColor, you just cast the sender object to correct type and set the new color.
private void picturebox_Click(object sender, EventArgs e)
{
var pictureBox = sender as PictureBox;
if (pictureBox != null) {
pictureBox.BackColor = Color.Blue;
}
}
On your event handler, sender contains the object that caused the event handler to fire. So by casting it to the correct type, we can then access all the properties as per this example:
private void picturebox_Click(object sender, EventArgs e)
{
PictureBox pic = (PictureBox)sender;
MessageBox.Show(pic.Name);
}
Note: code untested, not got access to VS to test

Categories