Add number when button was clicked - c#

I made an application which calculate the total price, I want that when the button is clicked, it add 1 to the quantity, but it only add 1 and when I click the button again, It doesn't add, Is there a way to loop a button?
here is my sample code
int intclicks;
private void button10_Click(object sender, EventArgs e)
{
intclicks++;
int qty = 1;
{
if (intclicks > 0)
{
int totalqty;
totalqty = qty + 1;
textBox3.Text = totalqty.ToString();
totalPrice();
}
}
}
the totalPrice(); sets display the total price in another textBox,
thanks.

You assign qty =1 in the beginning of the event, so, yes it starts from the beginning.
There is too much missing here, but it seems like you can use:
int qty = int.Parse(textBox3.Text);
...

When you click a button in a GUI-program, it fires the event once. Looping in the ClickEvent seems not very useful, as it would be blocking the main-thread and so your UI would freeze.
You could start a thread which loops in the background. See MSDN for threading.
Please explain further what you want to achieve.

That is because you have set int qty= 1 before your loop start and in your if condition you are checking if (intclicks > 0). So when you first time click the button it will check if (intclicks > 0) but as you have set qty = 1 the condition will be false and it wont go in the if condition. So change if condition to
if (intclicks >= 1)

I think your logic is a little out here for what (I believe) you are trying to do, why not try.
int intclicks;
int totalqty;
private void button10_Click(object sender, EventArgs e)
{
intclicks++;
if (intclicks > 0)
{
totalqty++
textBox3.Text = totalqty.ToString();
totalPrice();
intclicks = 0;
}
}

Related

How do I capture the "Enter" key in a windows form?

I am trying to get the text of a textbox and save it to a variable when the user presses the enter key (when the textbox has info and is focused) since this is already inside a method i haven't been able to put another method inside like txtbox1_keypress (or i've been doing it wrong) so I need to be just code lines that i can insert in this method
private void df1_Click(object sender, EventArgs e)
{
txtres.Focus();
//timer
timeLeft = 50;
timer1.Start();
//mult
do
{
ban = 0;
m1 = r.Next(1, 4);
txtm1.Text = m1.ToString();
m2 = r.Next(2, 6);
txtm2.Text = m2.ToString();
res = m1 * m2;
//here is where i want to read txtm2 and continue with the rest
if(txtres.Text == res.ToString())
{
pun++;
}
ban++;
} while (timeLeft > 0 || ban != 10);
if(pun == 10 && level == 0)
{
level++;
System.IO.File.WriteAllText(#".\level.lvl", level.ToString());
}
}
Since you mentioned you want to run it inside KeyPress event, here is the example:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (int) Keys.Enter)
{
//do the logic
}
}
Add a button as the accept button of the form, this will trigger whenever enter is pressed.
Also, your loop (do -- while) should be done within the timer1_tick method, and take out the loop, the timer will execute the code within every interval it ticks until the timer reaches your maximum of 50.
As was mentioned, the loop will kill your GUI and it wont allow input.

My form doesn't loop this correctly

I can't seem to get this loop to work.
Once the submit button is clicked ten times it should revert to the main form; instead it's reverting as soon as the submit is clicked once.
private void submit_Click(object sender, EventArgs e)
{
Form1 mainMenu = new Form1();
int repeat = 0;
do
{
num1.Text = A1.firstRandomNumber().ToString();
num2.Text = A1.secondRandomNumber().ToString();
repeat++;
} while (repeat <= 10);
if (repeat == 11)
{
mainMenu.Show();
this.Hide();
}
}
Everything inside of submit_Click occurs for each click. That includes defining repeat anew, setting it to 0, looping to increment it entirely to 11, and swapping which form is visible.
If you want to count the number of clicks, you'll have to establish your counter outside of the handler so it can be incremented:
private int repeatSubmit = 0;
private void submit_Click(object sender, EventArgs e)
{
if (repeatSubmit < 10)
{
num1.Text = A1.firstRandomNumber().ToString();
num2.Text = A1.secondRandomNumber().ToString();
repeatSubmit++;
}
else
{
mainMenu.Show();
this.Hide();
repeatSubmit = 0; // ready for the next time `this` form is shown
}
}
Just to clarify, you are waiting for the user to click the button 10 times? Or the loop is supposed to simulate 10 clicks?
This loop will enter (do) and set num1 and num2, add one to repeat, and then do that 10 times until repeat == 11, and then it will display the main menu.
I think the code you make be looking for is as follows:
private void submit_Click(object sender, EventArgs e)
{
...
repeat ++;
num1.Text = A1.firstRandomNumber().ToString();
num2.Text = A2.secondRandomNumer().ToString();
if(repeat >=10)
{
mainMenu.Show();
this.Hide();
}
}
As your code is, on 1 click you enter your loop where you proceed to increment the counter until it's equal to 11, then you exit your loop and show the main menu. Basically you're not counting clicks.
What you want to do is store the counter somewhere, probably as a class variable. Then every time you enter the click function you increment. When the click function has been entered 10 times then you would go into your if statement.
private int clickCount = 0;
private void submit_Click(object sender, EventArgs e){
clickCount++;
// Other code that happens on a click
if (clickCount == 10){ // 10th click show main menu
// Code to show main menu
}
}
It runs through the loop on the first click of submit, if I understand what you are trying to achieve, you don't need a loop at all, just a counter for each time the button is pressed.

Updating a Listbox Automatically

I have 2 listboxes. The first one is enabled and the second one is disabled. The second listbox will get its data from the first one.
For example, let's say I entered 2 in listbox1. listbox2 will get 2 + 1 = 3
Thing is, I want to update the second listbox automatically without clicking any button.
Is that even possible?
I wrote the following code in a button:
private void btnResult_Click(object sender, EventArgs e)
{
int WantedYear = Convert.ToInt32(txtForecastingYear.Text);
int FirstYearValue = WantedYear - 4;
txtFirstYear.Text = FirstYearValue.ToString();
int SecondYearValue = WantedYear - 3;
txtSecondYear.Text = SecondYearValue.ToString();
int ThirdYearValue = WantedYear - 2;
txtThirdYear.Text = ThirdYearValue.ToString();
int FourthYearValue = WantedYear - 1;
txtFourthYear.Text = FourthYearValue.ToString();
}
I want to do it without having to use a button to update. How can I do that?
Note: I'm using Windows Forms.
You can write your code in the SelectedIndexChanged event of the listbox. This event would be automatically fired as soon as the IndexChanges.
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
You can read more about it here.

How to count only checked items in CheckedListBox dynamically while the user is checking boxes?

I have a CheckedListBox control on my windows form application, which gives a list of items to select from.
I want to count and show only checked (not selected) items while the user is still checking them. I mean count as you check them.
I have tried to use ItemCheck event and CheckedListBox.CheckedItems.Count but the problem is that it counts every other click even if the item is unchecked. When I check something it counts and if I unchecked it again, it counts that too.
I think it has to do with the remark given on MSDN "The check state is not updated until after the ItemCheck event occurs." I do not completely understand the problem here.
Thank you.
The ItemCheckEventArgs parameter has the Property (NewValue) which tells you whether the change is a check, uncheck or neither.
If CheckedItems.Count is not updated until after the event fires (which is what I'm understanding from that remark) - then you can add that count, and see whether the ItemChecckEventArgs is a check (+1) or an uncheck (-1) and you can get the correct total.
(Unless I'm understanding the remark wrongly, its very vague).
Haedrian answered this correctly, but i think raw code goes a long ways too. So here's the C# code:
private void CheckedListBox_ItemCheck(Object sender, ItemCheckEventArgs e)
{
int sCount = checkedListBox.CheckedItems.Count;
if (e.NewValue == CheckState.Checked ) { ++sCount; }
if (e.NewValue == CheckState.Unchecked) { --sCount; }
// now sCount is count of selected items in checkedListBox.
}
I had the same issue, and this question and answer gave me the solution. Thanks for the question and already existing answers!
Add event handler for SelectedIndexChanged and get the count from CheckedItems.Count.
With ItemCheck you don't have the actual value, but value before the last change is processed and you would need to adjust the count according to EventArgs as Haedrian proposed.
Since we won't get the updated value in the CheckedItems.Count immediately, we use e.NewValue to get the updated value to get whether the state is Checked or not.
Declare a global variable for getting the count
int chkListCount = 0;
In the ItemCheck event give the following code
private void chkList_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (e.NewValue == CheckState.Checked)
{
chkListCount++;
}
else if(e.NewValue == CheckState.Unchecked)
{
chkListCount--;
}
}
Its the simple logic to get the count of selected items
It is not really a wise and intelligent work as a beginner but at the end solved my problem.
private void CheckedListBox_ItemCheck(Object sender, ItemCheckEventArgs e)
{
int count = 0;
if (e.NewValue.ToString() == "Checked")
{
// first get all the checked items
foreach (object checkeditem in CheckedListBox.CheckedItems)
{
string checkItem = CheckedListBox.GetItemCheckState(CheckedListBox.Items.IndexOf(checkeditem)).ToString();
if (checkItem == "Checked")
{
count = count + 1;
}
}
// Now, below is the most important part considering the remark on MSDN
// "The check state is not updated until after the ItemCheck event occurs."
count = count + 1; // Plus 1 as the NewValue was Checked
labelCount.Text = "You have selected " + count + "Items.";
}
else if (e.NewValue.ToString() == "Unchecked")
{
// first get all the checked items
foreach (object checkeditem in CheckedListBox.CheckedItems)
{
string checkItem = CheckedListBox.GetItemCheckState(CheckedListBox.Items.IndexOf(checkeditem)).ToString();
if (checkItem == "Checked")
{
count = count + 1;
}
}
// Now, below is the most important part considering the remark on MSDN
// "The check state is not updated until after the ItemCheck event occurs."
count = count - 1; // minus 1 as the NewValue was Unchecked,
labelCount.Text = "You have Selected " + count + "Items.";
}
}
I would really appreciate comments on this code.
I know this has been answered long ago, but I found it easier to just handle the MouseUp and KeyUp events. The CheckedItems.Count property is accurate when those events are fired. Since they both do the same thing, I created a method to to the work and called that method from both event handlers.
private void clbFolders_KeyUp(object sender, KeyEventArgs e) { Update(); }
private void clbFolders_MouseUp(object sender, MouseEventArgs e) { Update(); }
private void Update()
{
btnDelete.Enabled = clbFolders.CheckedItems.Count > 0;
}

Show items (checkboxes, radiobuttons etc...) by case (if...else...etc...)

I am trying to make a little game in C#.
The program asks the user for a any number.
The user then presses "GO" (button1) and the program checks whether the number is an even number or not. (x % 2 == 0)
I'm trying to get the program to show 4 checkboxes/radio buttons out of total of 8 depending on each case.
For example:
If the number is an EVEN NUMBER: The program will show options 2,5,3,6.
If the number is an ODD NUMBER: The program will show options 1,4,7,8.
(Options 1-8 were already included in the design.)
I need help with the if (x % 2 == 0) part. What do I write in it to make the checkboxes/radiobuttons appear or disappear?
By the way, is there a way to ask the user for a number without him having to click "GO"?
Like, use ENTER instead. If yes, what event is that?
Also, is there a way to limit the textbox to INT only?
I know it's asking you to do the job, but I have tried, and I'm still a real beginner, therefore I think my way of learning is by actually experiencing it.
public partial class Form1 : Form
{
int x;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
x = int.Parse(textBox1.Text);
if (x % 2 == 0)
{
}
}
}
The Visible property of the CheckBox (inherited from Control) will aid you in making the needed controls visible when you wish them to be. Your if would look something like,
if (num % 2 == 0)
{
box1.Visible = false;
box2.Visible = true;
// ...
}
else
{
box1.Visible = true;
box2.Visible = false;
// ...
}
However, this can be optimized a bit by using the condition to set the visibility of all the CheckBoxs at the same time instead of coding two conditionals - something like:
box1.Visible = !(num % 2 == 0);
box2.Visible = (num % 2 == 0);
// ...
As for on pressing enter, check the OnKeyDown event for you control, you can do this through the designer. Your event method would look like:
private void myControl_OnKeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
// Handle enter key pressed here
}
}
This should help you with your problems.
ADDITIONAL RESPONSE
List<CheckBox> boxes = new List<CheckBox>();
// Add all boxes and do other stuff, disable all
foreach (CheckBox box in boxes)
{
box.Visible = false;
}
In order to limit the textbox to int, you could override OnKeyPressed. As for your checkboxes, you could use the Visible or Checked properties.

Categories