Sum textboxes to other textbox wpf C# - c#

I have i wpf form with 3 textboxes there i should write how many tickets, then i want to multiply that number with a value
At the end i have another textbox there i want the sum from the 3 textboxes even if only 1 has value
i have tried this:
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
textBox3.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text)).ToString();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
textBox3.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text)).ToString();
}
Cant get it to work
Please help

To convert a string value to an integer value you may use int.Parse method. On the other hand this method (also Convert.ToInt32) requires you making sure that string is always in a good format to get converted. If you are not sure and/or you know that the string may be not in correct format, you may use int.TryParse method, which returns true/false value, stating whether the convert was succesful also giving out required value if it was successful. If it fails you get default value - 0.
If all textboxes follow same procedure you may create only one TextChanged event and bind it to all of them.
private void textBox1_TextChanged(object sender, EventArgs e)
{
int sum = 0;
if (!string.IsNullOrEmpty(textBox1.Text) && int.TryParse(textBox1.Text, out int gold_ticket_count))
{
sum += 120 * gold_ticket_count;
}
if (!string.IsNullOrEmpty(textBox2.Text) && int.TryParse(textBox2.Text, out int silver_ticket_count))
{
sum += 60 * silver_ticket_count;
}
if (!string.IsNullOrEmpty(textBox3.Text) && int.TryParse(textBox3.Text, out int big_show_ticket_count))
{
sum += 500 * big_show_ticket_count;
}
// do smth with the sum...
}
Check if I named textBoxes correctly. It is a good practise to give your controls a meaningful name.
int.Parse doc: https://learn.microsoft.com/en-us/dotnet/api/system.int32.parse?view=net-6.0
int.TryParse doc: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-6.0

an ugly, quick and dirty but working solution:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private int sum1;
private int sum2;
private int sum3;
private int overallSum;
private void tb1_TextChanged(object sender, TextChangedEventArgs e)
{
if (int.TryParse(tb1.Text, out int tb1Value))
sum1 = tb1Value * 120;
else
sum1 = 0;
sum_1.Text = sum1.ToString();
RecalcOverallSum();
}
private void tb2_TextChanged(object sender, TextChangedEventArgs e)
{
if (int.TryParse(tb2.Text, out int tb1Value))
sum2 = tb1Value * 120;
else
sum2 = 0;
sum_2.Text = sum2.ToString();
RecalcOverallSum();
}
private void tb3_TextChanged(object sender, TextChangedEventArgs e)
{
if (int.TryParse(tb3.Text, out int tb1Value))
sum3 = tb1Value * 120;
else
sum3 = 0;
sum_3.Text = sum3.ToString();
RecalcOverallSum();
}
private void RecalcOverallSum()
{
overallSum = sum1 + sum2 + sum3;
overall_sum.Text = overallSum.ToString();
}
}
BTW: I would recommend using MVVM instead of code behind, but I know it wasn't the question

Related

How do I update my label from selection of items in my listBox1 and listBox2?

So I have 2 list boxes within my form. Listbox1 contains different types of items that have a price and Listbox2 contains how much of that item you want to purchase. How do I update my price label so when I select both options from each list box it updates the label and gives me a price. Here's an example to help you better understand.
I select the $1.50 Chocolate Chip Cookie item in my ListBox1 and in ListBox2 I select the 1 Dozen Cookie item. So I would want my priceLabel to update to $18.00. How would I do this?
As of now I have tried creating some code in the listBox1_SelectedIndexChanged method but I am returned these 3 following values... $0.00...$2.00...$4.00
Here's my code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
double index = listBox1.SelectedIndex;
double index2 = listBox2.SelectedIndex;
double total = index * index2;
label9.Text = total.ToString("C");
}
private void label5_Click(object sender, EventArgs e)
{
}
private void label9_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
{
const int ESTIMATED_ARRIVAL = 3;
label10.Text = monthCalendar1.SelectionStart.AddDays(ESTIMATED_ARRIVAL).ToShortDateString();
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
In listBox1_SelectedIndexChanged(object sender, EventArgs e) you use listBox1.SelectedIndex; and listBox2.SelectedIndex;, if you refer to ListBox.SelectedIndex Property
ListBox.SelectedIndex Property
Gets or sets the zero-based index of the currently selected item in a
ListBox.
Property Value
Int32
A zero-based index of the currently selected item. A value of negative one (-1) is returned if no item is selected.
it just return index of selected item, so for your purpose you must get value of selected item.
I hope this code be a good guide for you:
Add handler of SelectedIndexChanged event of both list boxes to this method:
private void ListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.listBox1.SelectedIndex > -1 && this.listBox2.SelectedIndex > -1)//You can set default SelectedIndex for list boxes and remove this
{
string s1 = this.listBox1.Items[this.listBox1.SelectedIndex].ToString();
string s2 = this.listBox2.Items[this.listBox2.SelectedIndex].ToString();
//Now we extracting the number from string
//NOTE this is a simple implementation. You must change it as your needs.
//for example
//s1 = $1.50 Chocolate Chip Cookie
//s2 = 1 Dozen Cookie
int index = s1.IndexOf(' ');//get the index of first space after 1.50 (Number) in s1
s1 = s1.Substring(1, index);
index = s2.IndexOf(' ');//get the index of first space after 1 (Number) in s2
s2 = s2.Substring(0, index);
if (double.TryParse(s1, out double p1) && double.TryParse(s2, out double p2))
{
const int DOZEN = 12;
double result = p1 * (p2 * DOZEN);
//or
//remove const int DOZEN = 12; and simply
//double result = p1 * (p2 * 12);
this.label9.Text = result.ToString("C");
}
else
{
MessageBox.Show("Can not parse double values.");
}
}
}

Making values to perform addition in a single textbox

I recently got stuck in my project as I have requirements that I need to fulfil, the need to perform addition in a single textbox.
I've view the most similar posts and it gave a good idea of it, Addition using a single TextBox.
Instead of int, I am required to use double like how it was done with int.
private int i = 0;
private int[] a = new int[2];
private void button1_Click(object sender, EventArgs e)
{
int b;
if(Int32.TryParse(textBox1.Text, out b))
{
a[i] = b;
i++;
textBox1.Text = "";
}
else
{
MessageBox.Show(#"Incorrect number");
}
}
private void resultbutton2_Click(object sender, EventArgs e)
{
int sum = a[0] + a[1];
MessageBox.Show("Sum: " + sum);
}
}
Instead, what code should I use to create a similar things for double?
If you want to keep your code, just do this :
private int i = 0;
private double[] a = new double[2];
private void button1_Click(object sender, EventArgs e)
{
double b;
if (Double.TryParse(textBox1.Text, out b))
{
a[i] = b;
i++;
textBox1.Text = "";
}
else
{
MessageBox.Show(#"Incorrect number");
}
}
private void resultbutton2_Click(object sender, EventArgs e)
{
double sum = a[0] + a[1];
MessageBox.Show("Sum: " + sum);
}
But you can try this for adding more than 2 doubles :
private double result = 0.0;
private void button1_Click(object sender, EventArgs e)
{
double b;
if (Double.TryParse(textBox1.Text, out b))
{
result += b,
textBox1.Text = "";
}
else
{
MessageBox.Show(#"Incorrect number");
}
}
private void resultbutton2_Click(object sender, EventArgs e)
{
MessageBox.Show("Sum: " + result);
}
double b = 0;
try{
b = Convert.ToDouble(textBox1.Text);
}
catch(e){
// Error Handling
}
Docs: https://learn.microsoft.com/en-us/previous-versions/windows/apps/zh1hkw6k(v=vs.105)
you can try use something like:
Double.Parse("1.2");
some examples here:
https://msdn.microsoft.com/en-us/library/fd84bdyt(v=vs.110).aspx

Creating decreasing sequence with (x++)%n in C#

So, I know that with a code snippet such as:
int x = 0; //class field variable
private void button1_Click(object sender, EventArgs e)
{
Label1.Text += (x++)%4 + 1;
}
a sequence of 12341234 is displayed on the form if the button is clicked 8 times.
My goal is to get 43214321 to display.
I'm able to get 32103210 with:
int x = 0; //class field variable
private void button1_Click(object sender, EventArgs e)
{
Label1.Text += 3-(x++)%4;
}
I'm also able to get 32143214 with:
int x = 1; //class field variable
private void button1_Click(object sender, EventArgs e)
{
Label1.Text += 4-(x++)%4 + ;
}
What am I doing wrong? And is there a general formula for this?
Note: My x DOES have to be initialized to 1.
Just change the formula to:
Label1.Text += 4-((x-1)++)%4;
Try using this formula:
5-(1+(x+++3)%4)
That is:
Label1.Text += (5-(1+(x+++3)%4)).ToString();
The first line of code that you've written is basically cycling between 3 to 1.
x=0;
Label1.Text += 3-(x++)%4;
x=0 || Output=3.
Label1.Text= 0+3-(0%4)=3
x=1 || Output=2.
Label1.Text= 0+3-(1%4)=2
x=2 || Output=1.
(Dry run as done above)
x=3 || Output=0.
(dry run as done above)
x=4 and the cycle repeats.
You could dry run your second line of code to understand why your answer comes the way it does, but to answer your question in concise:
int x = 0; //class field variable
private void button1_Click(object sender, EventArgs e)
{
Label1.Text += 4-(x++)%4;
}

Increment number every time button is click

I want to increase an int variable i whenever I click on a button. But what I get is only int value of 1 and it doesn't increase anymore.
Here is my code:
private int i;
protected void btnStart_Click(object sender, EventArgs e)
{
i++;
lblStart.Text = i.ToString();
}
By each request (Clicking on the button), a new instance will be created.
So your non-static variable will be reset to 0.
You can define i as static:
private static int i;
protected void btnStart_Click(object sender, EventArgs e)
{
i++;
lblStart.Text = i.ToString();
}
But please note that the i variable is shared between all the users.
To improve this issue, you can use Session.
Session is an ability to store data of each user in a session.
So you can use following property to change the i variable in each session:
private int i
{
get
{
if (Session["i"] == null)
return 0;
return (int)Session["i"];
// Instead of 3 lines in the above, you can use this one too as a short form.
// return (int?) Session["i"] ?? 0;
}
set
{
Session["i"] = value;
}
}
protected void btnStart_Click(object sender, EventArgs e)
{
i++;
lblStart.Text = i.ToString();
}
As you know other answer is correct i want add another answer
You must in webform save your variables in ViewState
Just define your variables like this
public int i
{
get { Convert.ToInt32( ViewState["i"] ); }
set { ViewState["i"] = value ; }
}
Convert lblStart.Text value to int every time and assign it to i. Then increase i.
private int i;
protected void btnStart_Click(object sender, EventArgs e)
{
i = Int32.Parse(lblStart.Text);
i++;
lblStart.Text = i.ToString();
}
I have similar questions as yours and I believe the issue is because the event click did not store the value that has been increased before, therefore it could not be incremented the next time you clicked, so here's my code:
protected void btn_add_Click(object sender, EventArgs e)
{
string initial;
int increment;
int quantity;
initial = TextBoxQty.Text;
increment = Convert.ToInt16(initial);
increment++;
TextBoxQty.Text = increment.ToString();
quantity = increment;
}
You can use a hidden field, initialize them to 0.
private int i;
protected void btnStart_Click(object sender, EventArgs e)
{
i = int.Parse(myHiddenField.Value);
i++;
myHiddenField.Value = i;
lblStart.Text = i.ToString();
}
protected static int a = 0;
protected void btnStart_Click(object sender, EventArgs e)
{
a = a+1;
lblStart.Text = i.ToString();
}
It Works for me but on page_load() it initiates the value from 1 again !
this is actually my first time doing this
int i = 0;
while (i>=0)
{
Console.WriteLine(i);
Console.ReadLine();
i++;
}

winforms leave event and textchanged

I'm new to learning winforms and i'm stuck on the following problem and I do not think what I have done is the correct way, so any help would be appreciated.
I have 4 textboxes such as the following
private void txtBxPlayer1Bid_TextChanged(object sender, EventArgs e)
{
txtBxFundsAvialable.Text = (Convert.ToInt32(txtBxFundsAvialable.Text) - Convert.ToInt32(txtBxPlayer1Bid.Text)).ToString();
}
The 5th textbox txtBxFundsAvialable simple subtract the value of txtBxPlayer1Bid from txtBxFundsAvialable.
In designer.cs I have
this.txtBxPlayer1Bid.Leave += new System.EventHandler(this.txtBxPlayer1Bid_TextChanged);
The problem I have is, if I have 100 in txtBxFundsAvialable and enter 10 in txtBxPlayer1Bid the value in txtBxFundsAvialable should be 90, but txtBxPlayer1Bid etc seem to go into a loop and the value in txtBxFundsAvialable becomes 60. 4 textboxes X 10.
This happens for any of the 4 textboxes
The only way I can solve the problem is to set the values of the 4 textboxes to 0 in the txtBxFundsAvialable_TextChanged as shown below.
private void txtBxFundsAvialable_TextChanged(object sender, EventArgs e)
{
if (Convert.ToInt32(txtBxPlayer1Bid.Text) > 4 || (Convert.ToInt32(txtBxPlayer2Bid.Text)> 4 || (Convert.ToInt32(txtBxPlayer3Bid.Text)> 4) || (Convert.ToInt32(txtBxPlayer2Bid.Text)> 4)))
{
txtBxPlayer1Bid.Text = "0";
txtBxPlayer2Bid.Text = "0";
txtBxPlayer3Bid.Text = "0";
txtBxPlayer4Bid.Text = "0";
}
}
Is what I'm doing the correct way, as stated at the beginning, I'm new to winforms and it a canny leanning curve
I wrote a simple code with 2 textboxes that get values and a textbox with the result. Updates with TextChangedevent. Try to use it to fix your code..
private void textBox1_TextChanged(object sender, EventArgs e)
{
try
{
int num1 = Int32.Parse(textBox1.Text), num2 = Int32.Parse(textBox2.Text);
textBox3.Text = (num1 - num2).ToString();
}
catch { }
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
textBox1_TextChanged(sender, e);
}
EDIT
Try this code and link any of your "bid" textboxes to this function. textbox1 in this code is equivalent to your "available" textbox.
private void textBox_Leave(object sender, EventArgs e)
{
try
{
int num = Int32.Parse(((TextBox)sender).Text), available = Int32.Parse(textBox1.Text);
textBox1.Text = (available - num).ToString();
}
catch { }
}
Not sure how .Leave operates. Try to use .TextChanged or whatever the equivalent in WinForms.
All four (or even five) text boxes should use same event callback method.
Here is what you can do in that method:
private void txtBx_TextChanged(object sender, EventArgs e)
{
double player1 = 0, player2 = 0, player3 = 0, player4 = 0, total = 0;
if (int.TryParse(txtBxPlayer1Bid.Text, out player1)
&& int.TryParse(txtBxPlayer2Bid.Text, out player2)
&& int.TryParse(txtBxPlayer3Bid.Text, out player3)
&& int.TryParse(txtBxPlayer4Bid.Text, out player4)
&& int.TryParse(txtBxFundsAvialable.Text, out total)
{
total = player1 + player2 + player3 + player4;
}
}

Categories