Button Click Frequency Array - c#

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);
}

Related

Creating a dynamic button

I am trying to creat a dynamic button in a my application. So basically I have this code but when I run it I don’t see the bottom in the other form . The panel is empty. I create the bottom on a button click in a first form then it has to show the button in the second form’s panel.
private void btnsend_Click(object sender, EventArgs e)
{
this.Hide();
Form wrr = new Interface();
wrr.Show();
createnutton();
}
int i = 0;
int x = 0;
private void createnutton()
{
Button btn = new Button();
btn.Location = new Point(3 + i, 14 + x);
btn.BackColor = System.Drawing.Color.Red;
btn.ForeColor = System.Drawing.Color.Yellow;
btn.Text = "Tabel" + libtno.Text;
btn.Click += new EventHandler(btn_Click);
panel3.Controls.Add(btn);
i += 10;
x += 10;
}
void btn_Click(object sender,EventArgs e)
{
MessageBox.Show("me");
}
You have to set one more property "Visible=true" for your Button.
You need a reference to the instance of Interface that you created. Pass wrr to your createnutton function. For this to work, you have to change the MODIFIERS property of panel3 to PUBLIC. You also can't reference the Form with the generic Form type. It has to be of that specific Form type, which is Interface (a horrible name by the way, since interface has different meaning in C#):
private void btnsend_Click(object sender, EventArgs e)
{
this.Hide();
Interface wrr = new Interface();
wrr.Show();
createnutton(wrr); // <-- pass "wrr" to the function
}
int i = 0;
int x = 0;
private void createnutton(Interface frmInterface) // <-- parameter added
{
Button btn = new Button();
btn.Location = new Point(3 + i, 14 + x);
btn.BackColor = System.Drawing.Color.Red;
btn.ForeColor = System.Drawing.Color.Yellow;
btn.Text = "Tabel" + libtno.Text;
btn.Click += new EventHandler(btn_Click);
frmInterface.panel3.Controls.Add(btn); // <-- use the passed in form
i += 10;
x += 10;
}
BUT...this seems like a horrible design. I wouldn't do this if I were personally writing from the ground up.

delete listview item from another form - c#

I want to delete listview item from the main form
after I click on btn in another form
How can I do it?
Main Form
private void DeleteSelectedProductRclick_Click(object sender, EventArgs e)
{
int id = int.Parse(ProductListView.SelectedItems[0].SubItems[0].Text);
string prodname = ProductListView.SelectedItems[0].SubItems[1].Text;
string prodid = ProductListView.SelectedItems[0].SubItems[2].Text;
string cutsentence = null;
for (int i = 7; i >= 1; i--)
{
cutsentence = FirstWords(prodname, i);
if (cutsentence.Length <= 45)
{
cutsentence = cutsentence + " ...";
i = 0;
}
}
DeleteProductForm mg = new DeleteProductForm(id, cutsentence, prodid);
mg.Show();
}
Sec Form
private void Yesbtn_Click(object sender, EventArgs e)
{
EbaySellBL.EbayProduct.DeleteProduct(this.ID);
this.Close();
//ProductListView.SelectedItems[0].Remove();
}
You can make a control (your listview) public by opening the Properties tab in the winform designer and by changing the "Modifiers" property to "Public".
Now you can access it from another form.
More here

Create textboxs dynamically and shift focus to next texbox on click of "Enter" key in c# window form

I am developing an exe file
Which creates dynamic textboxes(no. of textboxes depends upon the user input in the one already provided textbox),
In the beginning it focus on the 1st textbox,
It should move focus to next textbox on click of "ENTER" key.
What I'm trying is:
private void Form1_Load(object sender, EventArgs e)
{
int a = 10;
for (int i = 1; i < 5; i++)
{
TextBox txtbx;
txtbx = new TextBox();
txtbx.Location = new Point(10, a);
a += 30;
this.Controls.Add(txtbx);
if(i==1)
{
txtbx.Focus();
}
}
}
public void Form1_KeyPessed(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.ENTER)
{
SendKeys.Send("{TAB}");
}
}
Need to use Control.TabIndex Property and you need to bind key down event for each newly created Text box
Try this :
private void Form1_Load(object sender, EventArgs e)
{
int a = 10;
for (int i = 1; i < 5; i++)
{
TextBox txtbx;
txtbx = new TextBox();
txtbx.Location = new Point(10, a);
txtbx.KeyDown += Txtbx_KeyDown; //Added
txtbx.TabIndex = i; //Added
a += 30;
this.Controls.Add(txtbx);
if (i == 1)
{
txtbx.Focus();
}
}
}
Now add Key down handler
//Added
private void Txtbx_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode.Equals(Keys.Enter))
{
SendKeys.Send("{TAB}");
}
}

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 events on Array of buttons

How can I get the name of the object last clicked on a panel? The trick is there is a big array of buttons on the panel (btn[1] ... btn [200]). How can I check if I clicked on button b[180], or b[11] or even outside the panel (no button)? Also the buttons are generated at page load via coding.
Thank you. Anna
EDIT:
Thank you! Another issue that arose (this generated a NULL object reference):
I have a method on the same level as buttonHandler(), it is named HowManyClicked() and it's called from within buttonHandler(). Inside HowManyClicked() I want to identify Button btn1 = Panel2.FindControl(x) as Button; where x is, for example, buttonArray[2,3]. But I always get NULL. Is the button array buttonArray not identifiable by name once out of the method that generated it??
public void buttonHandler(object sender, EventArgs e)
{
Button btn = sender as Button;
//string tt = btn.ToolTip.ToString();
btn.BackColor = Color.Red;
statusL.Text = HowManyClicked().ToString();
}
public int HowManyClicked()
{
int sum=0;
for (int a = 0; a < 10; a++)
for (int b = 0; b < 14; b++)
{
string x = "buttonArray[" + a + ", " + b + "]";
statusL.Text = x;
Button btn1 = Panel2.FindControl(x) as Button;
if (btn1.BackColor == Color.Red) sum += 1;
}
return sum;
}
As #AVD commented you can get the button originating the postback casting the sender object, you can also use the CommandName and CommandArgument properties from the button object (they are usually used when the button is inside a Grid, DataList etc but you can use them in this context if you need):
protected void Page_Init(object sender, EventArgs e)
{
var s = Enumerable.Range(1, 10);
foreach (var item in s)
{
var b = new Button();
b.Text = "My Button " + item.ToString();
b.CommandName = "custom command";
b.CommandArgument = item.ToString();
b.Click += new EventHandler(b_Click);
this.myPanel.Controls.Add(b);
}
}
void b_Click(object sender, EventArgs e)
{
var current = sender as Button;
this.lblMessage2.Text = "Clicked from array buttons: <br/>Command Name: " + current.CommandName + "<br/>Args: " + current.CommandArgument + "<br/>Button Unique ID: " + current.UniqueID + "<br/>Client ID: " + current.ClientID;
}
Page:
<asp:Panel runat="server" ID="myPanel">
</asp:Panel>
<asp:Label ID="lblMessage2" runat="server" />
This code generates something like:
As an additional note, Microsoft recommends to create dynamic controls in the PreInit event or in case you are using a master page, in the Init event
source
Edited
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.ViewState["count"] = 0;
}
}
protected void Page_Init(object sender, EventArgs e)
{
var s = Enumerable.Range(1, 10);
foreach (var item in s)
{
var b = new Button();
b.Text = "My Button " + item.ToString();
b.Click += new EventHandler(buttonHandler);
this.myPanel.Controls.Add(b);
}
}
void buttonHandler(object sender, EventArgs e)
{
// update here your control
var b = sender as Button;
b.BackColor = Color.Red;
HowManyClicked();
}
private void HowManyClicked()
{
var c = (int)this.ViewState["count"];
c++;
this.ViewState["count"] = c;
this.lblMessage2.Text = "Clicked controls: " + this.ViewState["count"].ToString();
}
This produced:
How can I get the name of the object last clicked on a panel?
The first parameter of click handler returns the reference of control/object has raised the event.
public void buttonHandler(object sender, EventArgs e)
{
Button btn=sender as Button;
....
}
I just figured out another fix by just redefining HowManyClicked() so I am adding it here below. Not sure still why the first method (the one in my question) didn't work also. Here goes:
public int HowManyClicked()
{
int sum=0;
foreach (Control cnt in this.Panel2.Controls)
if (cnt is Button)
{
Button btn = (Button)cnt;
if (btn.BackColor == Color.Red)
sum += 1;
}
return sum;
}
}
Thanks everyone!

Categories