How to divide two TextBoxes with a double and a int? - c#

private void button1_Click(object sender, EventArgs e)
{
int res = 0;
try
{
res = Convert.ToInt32(costot.Text) / Convert.ToInt32(unidadesp.Text);
costou.Text = res.ToString();
}
catch (Exception ex) { }
}

Not sure if this is what you are after but it should give you the syntax.
private void button1_Click(object sender, EventArgs e)
{
int res = 0;
if (double.TryParse(costot.Text, out double costot) && double.TryParse(unidadesp.Text, out double unidadesp) && unidadesp != 0)
{
res = (int)(Math.Round(costot / unidadesp));
costou.Text = res.ToString();
}
}
If you need the costot and unidadesp both changed to Integers before the division then do this.
res = (int)(Math.Round(Math.Round(costot) / Math.Round(unidadesp)));
One more edit
private void button1_Click(object sender, EventArgs e)
{
if (double.TryParse(textBox1.Text, out double costot) && int.TryParse(textBox2.Text, out int unidadesp) && unidadesp != 0)
{
var res = costot / unidadesp;
textBox3.Text = res.ToString();
}
}

Related

Numbers from textboxes are add next to each other instead of adding them together

I have 3 textboxes in which I write numbers and last one in which is the result. If I write numbers in TextBoxA and TextBoxB instead of adding them together after I press equal button then it put them next to each other.
[]
I tried this code:
private void EqualsButton_Click(object sender, EventArgs e)
{
OutputTextBox.Text = ($"{InputTextBoxA.Text + InputTextBoxB.Text}");
}
First you must convert text on textbox to int or any number type
Simple way :
private void EqualsButton2_Click(object sender, EventArgs e)
{
int numberA = int.Parse(textBox1.Text.Trim());
int numberB = int.Parse(textBox2.Text.Trim());
var result = numberA + numberB;
textBox3.Text = result.ToString();
}
Safe way :
private void EqualsButton_Click(object sender, EventArgs e)
{
if (!int.TryParse(textBox1.Text.Trim(), out int numberA))
numberA = 0;
if (!int.TryParse(textBox2.Text.Trim(), out int numberB))
numberB = 0;
var result = numberA + numberB;
textBox3.Text = result.ToString();
}
Don't listen to anyone. Do this
txtResult.Text = string.Empty;
if (!decimal.TryParse(txt1.Text.Trim(), out decimal v1))
{
MessageBox.Show("Bad value in txt1");
return;
}
if (!decimal.TryParse(txt2.Text.Trim(), out decimal v2))
{
MessageBox.Show("Bad value in txt2");
return;
}
txtResult.Text = (v1 + v2).ToString();
private void EqualsButton_Click(object sender, EventArgs e)
{
var resultA=0;
var resultB=0;
if(!string.IsNullOrEmpty(InputTextBoxA.Text))
resultA=Convert.ToInt32(InputTextBoxA.Text);
if(!string.IsNullOrEmpty(InputTextBoxB.Text))
resultB=Convert.ToInt32(InputTextBoxB.Text);
OutputTextBox.Text = resultA+ resultB ;
}
You can change into this
private void EqualsButton_Click(object sender, EventArgs e)
{
try
{
OutputTextBox.Text = ($"{ Convert.ToInt32(InputTextBoxA.Text.Trim() == "" ? "0" : InputTextBoxA.Text) + Convert.ToInt32(InputTextBoxB.Text.Trim() == "" ? "0" : InputTextBoxB.Text)}");
}
catch(exception ex)
{
MessageBox.Show("Enter Valid number")'
}
}
You need to convert text fields to int and after for the answer back to the text.
If you did not enter a value, then there "" is considered as 0 when adding.
private void EqualsButton_Click(object sender, EventArgs e)
{
OutputTextBox.Text = Convert.ToString(
Convert.ToInt32(InputTextBoxA.Text == "" ? "0" : InputTextBoxA.Text)
+ Convert.ToInt32(InputTextBoxB.Text == "" ? "0" : InputTextBoxB.Text));
}

Decrementing a double value using a button puts it back to 0. C#

I am using a text box to show quantity. Using 2 buttons I want to increment or decrements a value. So far increment works but when I try to decrement the same value it puts it back to 0 instead of going from 5 to 4.
private void button3_Click(object sender, EventArgs e)
{
double val = double.Parse(textBox1.Text);
while (val != 0)
{
val--;
}
textBox1.Text = val.ToString();
}
This is the code I am using.
You are using a while loop. That means it will decrement the value until it becomes 0.
Change your while to an if and it should work as expected.
private void button3_Click(object sender, EventArgs e)
{
double val = double.Parse(textBox1.Text);
if (val != 0)
val--;
textBox1.Text = val.ToString();
}
You are using while construction that does val-- util it is 0
In your case you simply need to do this:
private void button3_Click(object sender, EventArgs e) {
double val = double.Parse(textBox1.Text);
if (val > 0)
val--;
textBox1.Text = val.ToString();
}
In addition I recommend you to use double.TryParse method. So you don't need to add try ... catch statement:
private void button3_Click(object sender, EventArgs e) {
double val;
bool perseOk = double.TryParse(textBox1.Text, out val);
if (perseOk && val > 0) {
val--;
} else {
val = 0;
}
textBox1.Text = val.ToString();
}

freezing form after clicking button

I have a problem regarding to payment button.
I don't encounter an error before building, but after building and clicking the payment button it hangs. I think its because of lblTotalPrice.text, but I don't know how to fix it.
public partial class Form1 : Form
{
int totalCost;
public double holDer;
public Form1()
{
InitializeComponent();
this.cbo1.Items.AddRange(new object[] { "Lechon Kawali - 200", "Bicol Express - 300"
,"Adobo - 350" });
}
private void btnAdd_Click(object sender, EventArgs e)
{
lb1.Items.Add(cbo1.SelectedItem);
lb1.SelectedIndex = lb1.SelectedIndex ;
int z = 0;
if (cbo1.SelectedIndex == 0)
{
z = z + 1;
}
if (cbo1.SelectedIndex == 1)
{
z = z + 2;
}
if (cbo1.SelectedIndex == 2)
{
z = z + 3;
}
switch(z)
{
case 1:
totalCost = totalCost + 200;
break;
case 2:
totalCost = totalCost + 300;
break;
case 3:
totalCost = totalCost + 350;
break;
}
lblSubTotalCost.Text = ("Php " + totalCost.ToString());
}
private void btnDelete_Click(object sender, EventArgs e)
{
int deleteCost = 0;
int itemCost = 0;
foreach (int selectedIndex in lb1.SelectedIndices)
{
itemCost = int.Parse(lb1.Items[selectedIndex].ToString().Split('-')[1]);
deleteCost += itemCost; lb1.Items.RemoveAt(selectedIndex);
}
totalCost = totalCost - deleteCost;
lblSubTotalCost.Text = ("Php " + totalCost.ToString());
lb1.Items.Remove(lb1.SelectedItem);
if (lb1.Items.Count > 0)
{
lb1.SelectedIndex = 0;
}
else
MessageBox.Show("No orders");
}
private void lblVAT_TextChanged(object sender, EventArgs e)
{
Add();
}
private void lblSubTotalCost_TextChanged(object sender, EventArgs e)
{
multiply();
Add();
}
public void multiply()
{
int a;
double b = 0.12;
bool Valid = int.TryParse(totalCost.ToString(), out a);
if (Valid)
lblVAT.Text = (a * b).ToString();
else
lblVAT.Text = "No VAT entered";
}
private void lbTotalPrice_TextChanged(object sender, EventArgs e)
{
Add();
}
public void Add()
{
int a;
int b;
bool AValid = int.TryParse(totalCost.ToString(), out a);
bool BValid = int.TryParse(lblVAT.Text, out b);
if (AValid && BValid)
{
lblTotalPrice.Text = ("Php " + (a + b).ToString());
}
}
private void btnPayment_Click(object sender, EventArgs e)
{
holDer = double.Parse(tbPayment.Text) - double.Parse(lblTotalPrice.Text);
MessageBox.Show("Change: " + holDer.ToString());
}
}
As you stated in your comments, your problem it is not that your application hangs, but the problem is that you are getting a Input string was not in a correct format Exception.
That it seems is from this block:
private void btnPayment_Click(object sender, EventArgs e)
{
holDer = double.Parse(tbPayment.Text) - double.Parse(lblTotalPrice.Text);
MessageBox.Show("Change: " + holDer.ToString());
}
As it is a not very complex code, your problem seems to be when you are casting your textboxes to Double. Be sure that you are using the correct separator for double values and that you not have any strange characters in tbPayment
Try using TryParse method:
double res;
if(double.TryParse(tbPayment.Text, out res))
{
holDer = res - double.Parse(lblTotalPrice.Text);
MessageBox.Show("Change: " + holDer.ToString());
}
else
{
MessageBox.Show("Input a correct format");
}
I suspect it's because the lblTotalPrice_TextChanged event-handler calls Add() which then changes the lblTotalPrice.Text property, causing the event to fire again, ad -infinitum?

Don't let me add in a listbox more items than shown in the combobox

I have a combobox with the items
1
2
3
...
40
,if I chose the value 4 then I should be able to add in my listbox no more than 4 values.This is what i was thinking of but isn't working.
public Form1()
{
InitializeComponent();
}
private void add_Click(object sender, EventArgs e)
{
int allowedItemsCount = 0;
Int32.TryParse(comboBox1.SelectedText, out allowedItemsCount);
int currentItemsCount = listBox1.Items.Count;
if (currentItemsCount < allowedItemsCount)
{
listBox1.Items.Add(textBox1.Text);
}
}
private void delete_Click(object sender, EventArgs e)
{
if (listBox1.SelectedItems.Count != 0)
{
while (listBox1.SelectedIndex != -1)
{
listBox1.Items.RemoveAt(listBox1.SelectedIndex);
}
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int x = 0;
Int32.TryParse(comboBox1.SelectedText, out x);
int count = listBox1.Items.Count;
if (count > x)
{
listBox1.Items.Clear();
int difference = count - x;
for (int i = 0; i < difference; i++)
{
listBox1.Items.RemoveAt(listBox1.Items.Count - 1);
}
}
}
}
Here is the full code you asked for but is not working...now the add button is not working.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int x = 0;
Int32.TryParse(comboBox1.SelectedText, out x);
int count = listBox1.Items.Count;
if (count > x)
{
listBox1.Items.Clear();
int difference = count - x;
for(int i = 0 ; i < difference ; i++)
{
listBox1.Items.RemoveAt(listBox1.Items.Count-1);
}
}
}
Update
As per your comment, write this code in your add button click event
int allowedItemsCount = 0;
Int32.TryParse(comboBox1.SelectedText, out allowedItemsCount);
int currentItemsCount = listBox1.Items.Count;
if(currentItemsCount < allowedItemsCount)
{
listBox1.Items.Add(textBox1.Text); // I assume your textbox id is TextBox1
}
For removing extra items:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
listBox1.TrimExcess(Int32.Parse(comboBox1.SelectedText));
//If you control the items on the combo so you know for sure the parse will work, ignore the tryparse
}
And for adding items to the ListBox (and control it does not have to much items:
private int addToListBox(object item)
{
if(listbox1.items.count>=Int32.Parse(comboBox1.SelectedText)) return -1;
listbox1.items.add(item);
return 0;
}
And when you need to add to that listbox use addToListBoxand not listbox1.items.add
This will check if you can add line to listbox1 and if its changed number of line it will delete it.
Adding is made by button.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int x = 0;
Int32.TryParse(comboBox1.SelectedItem.ToString(), out x);
int count = listBox1.Items.Count;
while(count > x){
listBox1.Items.RemoveAt(count - 1);
count = listBox1.Items.Count;
}
}
private void button2_Click(object sender, EventArgs e)
{
int x = 0;
Int32.TryParse(comboBox1.SelectedItem.ToString(), out x);
if (listBox1.Items.Count < x)
{
listBox1.Items.Add(x); //add whatever you want
}
}

Multiplication in C# WPF

I'm trying to make a program that generates 2 random numbers, then, after the user inputs the multiplication of those numbers, it will tell the user in a MessageBox whether or not the user was right or wrong. Sort of like an educational simulator.
I'm having problems with the end part. What I'm saying is; If the answer is the same as number1 and number2 multiplied, then it says; "Rétt!" and if not; "Rangt..."
Any ideas?
private void bt_end_Click(object sender, RoutedEventArgs e)
{
int number1 = 0;
int number2 = 0;
int answer = 0;
tbnumber1.Text = number1.ToString();
tbnumber2.Text = number2.ToString();
if (svar == (number1 * number2))
{
MessageBox.Show("Rétt!");
}
else
{
MessageBox.Show("Rangt...");
}
}
}
}
The full code.
public MainWindow()
{
InitializeComponent();
}
int tala1 = 0;
int tala2 = 0;
int svar = 0;
private void btstart_Click(object sender, RoutedEventArgs e)
{
tbtala1.Text = "";
tbtala2.Text = "";
tbsvar.Text = "";
Random random = new Random();
tala1 = random.Next(1, 11);
tala2 = random.Next(1, 11);
tbtala1.Text = tala1.ToString();
tbtala2.Text = tala2.ToString();
}
private void btend_Click(object sender, RoutedEventArgs e)
{
tbtala1.Text = tala1.ToString();
tbtala2.Text = tala2.ToString();
tbsvar.Text = svar.ToString();
if (svar == (tala1 * tala2).ToString())
{
MessageBox.Show("Rétt!");
}
else
{
MessageBox.Show("Rangt... :(");
}
}
}
}
SOLVED. Thank you to everyone who did/tried to help.
Final Version:
Final Version:
public MainWindow()
{
InitializeComponent();
}
int tala1 = 0;
int tala2 = 0;
int svar = 0;
private void btstart_Click(object sender, RoutedEventArgs e)
{
tbtala1.Text = "";
tbtala2.Text = "";
tbsvar.Text = "";
Random random = new Random();
tala1 = random.Next(1, 11);
tala2 = random.Next(1, 11);
tbtala1.Text = tala1.ToString();
tbtala2.Text = tala2.ToString();
}
private void btend_Click(object sender, RoutedEventArgs e)
{
tala1 = Convert.ToInt32(tbtala1.Text);
tala2 = Convert.ToInt32(tbtala2.Text);
svar = Convert.ToInt32(tbsvar.Text);
if (svar == (tala1 * tala2))
{
MessageBox.Show("Rétt!");
}
else
{
MessageBox.Show("Rangt... :(");
}
To do this in a safe manner, you should not only Parse the text inputs to numbers, but you should also ensure that the text does in fact contain numbers first. If your numbers are supposed to be integers then you could use this:
private void bt_end_Click(object sender, RoutedEventArgs e)
{
int number1 = 0;
int number2 = 0;
if (int.TryParse(tbnumber1.Text, out number1) ||
int.TryParse(tbnumber12.Text, out number2)) MessageBox.Show("Rangt...");
MessageBox.Show(svar == number1 * number2 ? "Rétt!" : "Rangt...");
}
You're putting the numbers in the textbox values. you have to convert textbox values to numbers.
private void btend_Click(object sender, RoutedEventArgs e)
{
try{
tala1 = Convert.ToInt32(tbtala1.Text);
tala2 = Convert.ToInt32(tbtala2.Text);
svar = Convert.ToInt32(tbsvar.Text);
if (svar == (tala1 * tala2))
{
MessageBox.Show("Rétt!");
}
else
{
MessageBox.Show("Rangt... :(");
}
}catch{
MessageBox.Show("Invalid input");
}
}
You never define svar. You probably meant something like this, assuming svar was set earlier and is the correct product of the random multiplication:
private void bt_end_Click(object sender, RoutedEventArgs e)
{
int number1 = 0;
int number2 = 0;
number1 = int.Parse(tbnumber1.Text);
number2 = int.Parse(tbnumber2.Text);
if (svar == (number1 * number2))
{
MessageBox.Show("Rétt!");
}
else
{
MessageBox.Show("Rangt...");
}
}
1.I observed that you have not initialized variable 'svar' anywhere.
Initialise your svar variable with proper value.
2.Replace This :
if (svar == (number1 * number2).ToString())
With Following :
if (svar == (number1 * number2))

Categories

Resources