Why do i keep getting these errors? - c#

Im trying to write a program in C# that allows the user to input the number of seats sold, then the program multiples each number by the price to get how many were bough in each section. Ive gotten to the end but he program is not working because of the red line under the texbox.toString part. Can someone help me know what my errors are?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label7_Click(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
textBox4.Text = "";
textBox3.Text = "";
textBox2.Text = "";
total.Text = "";
input1.Text = "";
input2.Text = "";
input3.Text = "";
}
private void button1_Click(object sender, EventArgs e)
{
int input1;
int input2;
int input3;
input1 = int.Parse(input1.ToString());
input2 = int.Parse(input2.ToString());
input3 = int.Parse(input3.ToString());
int sum1 = input1 * 15;
int sum2 = input2 * 12;
int sum3 = input3 * 9;
sum1 = textBox3.ToString();
sum2 = textBox2.ToString();
sum3 = textBox4.ToString();
}
}

to obtain the string written in your textBox:
textBox.Text;
to display a value sum in textBox:
textBox.Text = sum.ToString();
This is how button1_Click would look like at least:
private void button1_Click(object sender, EventArgs e)
{
int in1; // change int names to not confuse woth textboxes
int in2;
int in3;
in1 = int.Parse(input1.Text); // input1 is textBox
in2 = int.Parse(input2.Text);
in3 = int.Parse(input3.Text);
int sum1 = in1 * 15;
int sum2 = in2 * 12;
int sum3 = in3 * 9;
textBox3.Text = sum1.ToString();
textBox2.Text = sum2.ToString();
textBox4.Text = sum3.ToString();
}

You can use just
int.Parse(textbox.Text);

Use the "Text" property of the text box control instead. It would be better to have it as something like "input1.Text.Trim()", as this would remove any leading/trailing spaces that accidentally got into the input.
As a best practice, particularly while getting values from text controls in UI, it is good to use Int32.TryParse. (Please see: Parse v. TryParse)
As an additional point, your code does not follow basic naming conventions.

sum is an integer but textBox.ToString() is a string. You can't assign a string into an integer
it should be
textBox3.Text = sum1.ToString();

The problem is occurring because you are attempting to store the value of a string into an int.
The line:
sum = textBox.ToString();
is just converting the value of textBox to a string, not the value of the text in textBox, and passing it into the sum variable. That won't work.
Try this instead:
sum = Convert.ToInt32(textBox.Text);
However, if you ever want to show the value of sum in textBox, you can implicitly convert from an int to a string:
textBox.Text = sum;

Related

How to sum all numbers in a Listbox using TextBox?

I want to count and sum all values in a ListBox. For example, I have the following values in my ListBox: 4, 6, 1, 7. My current value is 18. If I add a 2 with a TextBox, I need to get 20 and if I add 5 I need to get 25 in total.
If I try it with the below code, it gives me a whole other number.
Here is my code:
private void AddButton_Click(object sender, EventArgs e)
{
decimal sum;
listBox2.Items.Add(TextBox1.Text);
TextBox1.Text = "";
for (int i = 0; i < listBox2.Items.Count; i++)
{
sum += Convert.ToDecimal(listBox2.Items[i].ToString());
}
Label1.Text = sum.ToString();
}
You missed to initialize default value of sum. Assign sum = 0 before adding values to sum variable
private void AddButton_Click(object sender, EventArgs e)
{
decimal sum = 0; //Set sum = 0 by default
listBox2.Items.Add(TextBox1.Text);
TextBox1.Text = "";
for (int i = 0; i < listBox2.Items.Count; i++)
{
//To check value of sum after each iteration, you can print it on console
Console.WriteLine("Sum =" +sum);
sum += Convert.ToDecimal(listBox2.Items[i].ToString());
}
Label1.Text = sum.ToString();
}
Sorry for maybe not answer but it is strange that your compiler didn't tell you to initialize sum. The second I tested your code and it works correctly as expected that means that if the problem is not in sum variable then you made something else to this fields somewhere else so your code doesn't work correctly.
Having in mind your comment to previous person I'd say the same. In some cases (I know it's funny but) you may have viruses on your computer. Check it. Once in my life I've failed my maths lab work because of virus that interrupted my program so it drew the wrong chart !sick I know :D
private void button1_Click(object sender, EventArgs e)
{
var sum = 0;
var value = 0;
listBox1.Items.Add(textBox1.Text);
foreach (var item in listBox1.Items)
{
if (!int.TryParse(item.ToString(), out value))
continue;
sum = sum + value;
}
label1.Text = sum.ToString();
textBox1.Text = string.Empty;
}
Use of unassigned local variable 'sum', sum must be assigned before use !
decimal sum = 0;
Rest all is ok
Need to set sum to 0 and also it is probably best to use a foreach instead of a Dotloop.
private void AddButton_Click(object sender, EventArgs e) {
decimal sum = 0;
listBox2.Items.Add(TextBox1.Text);
TextBox1.Text = "";
foreach (string s in listBox2) {
sum += Convert.ToDecimal(s);
}
Label1.Text = sum.ToString();
}

C# Calculator using List Array error at some operations Windows Form Application

Hello I'm still new to programming and yes this is not the best code you will see... I tried making calculator on C# windows form for fun and I'm having trouble on the subtraction and division operations, but the addition and multiplication works perfectly fine for me. I decided to have a list array so that I would be able to input numbers as much as I want.
The error for the subtraction is when I input for example 5 - 2 the result will be -3
As for the division the error is that the result is always 1
Please tell me where did I go wrong and give a detailed explanation if possible so that I would understand more about programming. Thanks in advance!
namespace CalculatorTestForm1
{
public partial class Form1 : Form
{
public static List<int> Numlist = new List<int>();
public static string operation;
public Form1()
{
InitializeComponent();
}
private void Button_Click(object sender, EventArgs e)
{
Button Num = (Button)sender;
TXTBox.Text += Num.Text;
}
private void BPlus_Click(object sender, EventArgs e)
{
operation = "add";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
private void BEquals_Click(object sender, EventArgs e)
{
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
int sum = 0;
int product = 1;
int quotient = 1;
int difference = 0;
if (operation == "add"){
foreach (int value in Numlist)
{
sum += value;
}
string Answer = sum.ToString();
TXTBox.Text = Answer;
}else if(operation == "minus"){
foreach (int value in Numlist)
{
difference = value - difference;
}
string Answer = difference.ToString();
TXTBox.Text = Answer;
}
else if (operation == "multiply")
{
foreach (int value in Numlist)
{
product *= value;
}
string Answer = product.ToString();
TXTBox.Text = Answer;
}
else if (operation == "divide")
{
foreach (int value in Numlist)
{
quotient = value / value;
}
string Answer = quotient.ToString();
TXTBox.Text = Answer;
}
Numlist.Clear();
}
private void BClear_Click(object sender, EventArgs e)
{
TXTBox.Text = "";
Numlist.Clear();
}
private void BMinus_Click(object sender, EventArgs e)
{
operation = "minus";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
private void BDivide_Click(object sender, EventArgs e)
{
operation = "divide";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
private void BMulti_Click(object sender, EventArgs e)
{
operation = "multiply";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
}
}
For the division it's obvious:
quotient = value / value;
value/value will always be 1.
There must be quotient in that loop somewhere...
For the subtraction the problem is that because of the way you do it, the order of the numbers are reversed.
lets say 5 - 2:
foreach (int value in Numlist)
{
difference = value - difference;
}
NumList = {5,2}
1st iteration:
difference = value(5) - difference(0) = 5
2nd iteration:
difference = value(2) - difference(5) = -3
You should reverse the order of the loop: NumList.Reverse()
And for the division as well:
Division:
foreach (int value in Numlist.Reverse())
{
quotient = value / quotient;
}
Subtraction:
foreach (int value in Numlist)
{
difference = value - difference;
}

Fill a textbox based on another textbox text

I have TextBoxA and TextBoxB. What i want to do is , whenever i put a number (yes, both of the textboxes values are always integers) in TextBoxA , TextBoxB should "autocomplete" with value (100-TextBoxA). Same thing goes for TextBoxB. The sum of TextBoxA and TextBoxB should always be 100.
Here's what i've already tried:
static void TextBoxA_TextChanged()...
{
int a = Convert.ToInt32(TextBoxA.Text);
int b = Convert.ToInt32(TextBoxB.Text);
string text = (100-a).ToString();
TextBoxB.Text = text;
}
Static void TextBoxB_TextChanged()...
{
int a = Convert.ToInt32(TextBoxA.Text);
int b = Convert.ToInt32(TextBoxB.Text);
string text = (100-b).ToString();
TextBoxA.Text = text;
}
But it doesn't work.
Here's what you can try:
private void TextBoxA_TextChanged(object sender, EventArgs e)
{
int num = 0;
if (int.TryParse(TextBoxA.Text, out num))
{
string text = (100 - num).ToString();
TextBoxB.Text = text;
}
}
private void TextBoxB_TextChanged(object sender, EventArgs e)
{
int num = 0;
if (int.TryParse(TextBoxB.Text, out num))
{
string text = (100 - num).ToString();
TextBoxA.Text = text;
}
}
This will autocomplete on either TextBox on TextChanged Event.
First, i dont know why your event handlers are declared static.. its usually got to be :
private void TextBoxA_TextChanged(object sender, EventArgs e) { }
Secondly, you know if you have 2 textboxs, and each one triggers the other, you'll never go out of the TextChanged event.
To understand me more, here's an example :
1- You set TextBoxB.text = "1";2- TextBoxB.TextChanged triggers, it
sets TextBoxA.Text = "2"; 3- TextBoxA.TextChanged triggers, it sets
TextBoxB.Text = "1";
And it continues like this until i believe you'll get an Exception of memory.
EDIT : The opertator '-' works on numbers. You can't substract a number from a string. they have to be both numbers, so convert them first.
EDIT 2 :
Here's a code i wrote that works fine
private void textBox1_TextChanged(object sender, EventArgs e)
{
int n;
if (int.TryParse(textBox1.Text, out n)) // Check if the text value is a number
{
if (n > 100) // Since you want a sum of 100
return;
int m = 100 - n; // remaining
if (textBox2.Text != m.ToString()) // to not re-trigger the TextChanged event
textBox2.Text = m.ToString();
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
int n;
if (int.TryParse(textBox2.Text, out n)) // Check if the text value is a number
{
if (n > 100) // Since you want a sum of 100
return;
int m = 100 - n; // remaining
if (textBox1.Text != m.ToString()) // to not re-trigger the TextChanged event
textBox1.Text = m.ToString();
}
}
Try this. This is a more efficient and elegant way I'd choose using lambda expressions, without repeating the method:
private void onChangeDoSum(object sender, EventArgs e,
TextBox substractNumber, TextBox sumNumber)
{
sumNumber.Text = (100 - Int32.Parse(substractNumber.Text)).ToString();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.TextChanged += (a, b) => onChangeDoSum(sender, e, textBox1, textBox2);
textBox2.TextChanged += (a, b) => onChangeDoSum(sender, e, textBox2, textBox1);
}
Alternatively use Int32.TryParse to prevent unexpected results.
I think you can do something like this
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox2.Text = (100 - Int32.Parse(textBox1.Text)).ToString();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
textBox1.Text = (100 - Int32.Parse(textBox2.Text)).ToString();
}
when I see that static word I think you have tried to create these method by yourself and you forgot to add
textBox1.TextChanged += textBox1_Changed;
// I saw other post where you wrote that it could raise exception and fall. Of course it can. You can use if condition like
textBox1.Text != null && textBox1.Text != ""
before value would be changed or TryParse() method

Store textbox value into a string?

I am making a random number generator in a form application and the user will type a number in a text box. When user clicks on the OK button. the text in the textbox will be stored in a string value. for example;
if (ButtonOK is clicked)
{
String a = textbox1;
int b = int.Parse(a);
}
Then the value of the textbox will become a labels value. for example:
b = label1.Text;
how do i do that?
I would be really happy if anyone could help me solve this problem.
SOLVED thanks to Soner Gönül
I feel like you need something like;
private void ButtonOK_Click(object sender, EventArgs e)
{
string a = textbox1.Text;
int b;
if (Int32.TryParse(a, out b))
{
label1.Text = b.ToString();
}
}
Assuming is a WinForm application just drag a button and a textbox on the form, double click on the button and write this code:
private void button1_Click(object sender, EventArgs e)
{
int max;
if (!int.TryParse(textBox1.Text, out max))
{
label1.Text = "Not a number";
}
else
{
Random r = new Random();
int random = r.Next(max);
label1.Text = string.Format("Random number: {0}", random);
}
}

error Input string was not in a correct format in the first line int a

private void txtrate_TextChanged(object sender, EventArgs e)
{
int a = Convert.ToInt32(txtqty.Text);
int b = Convert.ToInt32(txtrate.Text);
int c = a * b;
txttotal.Text = Convert.ToString(c);
//txttotal.Text = (Convert.ToInt32(txtqty.Text) * Convert.ToInt32(txtrate.Text)).ToString();
}
Well... this error occurs of txtqty.Text (or txtrate.Text for variable b) does not contain a valid number. So the user entered letters or other characters instead of 0 till 9.
You could try to validate your input first with TryParse:
private void txtrate_TextChanged(object sender, EventArgs e)
{
int a = Convert.ToInt32(txtqty.Text);
int b = Convert.ToInt32(txtrate.Text);
if (Int32.TryParse(txtqty.Text, out a) && (Int32.TryParse(txtrate.Text, out b)
{
int c = a * b;
txttotal.Text = c.ToString();
}
}
Yes, this is due to the value not contained only numbers, to avoid this situation, please setup the type of data you are trying to collect with the text fields, you can setup refer this post for a detailed walk through on how to do it.
Yes, I would suggest TryParsetoo :
private void txtrate_TextChanged(object sender, EventArgs e)
{
int number;
bool result = Int32.TryParse(txtqty.Text, out number);
if (result)
{
//Converting is Ok, proceed
}
else
{
//Convertign fail
txtqty.Focus();
MessageBox.Show("Please enter only number for this field");
return;
}
}
I would suggest making this for each textbox with setting the focus to the textbox with incorrect input and providing an useful message for the user. In my opinion this is a suitable and user-friendly way.

Categories

Resources