converting textbox string to int - c#

I'm trying to compare and multiply 2 random number variables with the int value entered in textboxes. If it is the correct increment the correct answers it does not increase the number although it increment works alone but it does not work with the textbox.
private void button1_Click(object sender, EventArgs e)
{
int x = Randomnumber.Next(12);
int z = Randomnumber.Next(12);
//int cv = +correct;
textBox2.Text = x.ToString();
textBox3.Text = z.ToString();
int s = x * z;
if (s == int.Parse(textBox4.Text))
{
correct++;
numbercorrect.Text = correct.ToString();
}
}

EDIT This is assuming that you are trying to have the user enter their guess before the button is pressed. Figured I would put this disclaimer here since there is confusion exactly what you are trying to do.
Looking at your current code sample, you are trying parse textBox4.Text, however, you are not setting textBox4.Text anywhere in your code sample. If textBox4.Text is string.Empty, int.Parse will throw an exception.
You should also look into doing Int.TryParse as it will tell you if it worked without throwing an exception.
EDIT: Since this is a guessing game, you should be validating the user's entry in textBox4 before continuing.
private void button1_Click(object sender, EventArgs e)
{
int answer;
if(!int.TryParse(textBox4.Text, out answer))
{
MessageBox.Show("Please Enter A Valid Integer.");
return;
}
int x = Randomnumber.Next(12);
int z = Randomnumber.Next(12);
//int cv = +correct;
textBox2.Text = x.ToString();
textBox3.Text = z.ToString();
int s = x * z;
if (s == answer)
{
correct++;
numbercorrect.Text = correct.ToString();
}
}

You're comparing the textbox value to the product of two random values. Unless you know what those two random numbers are before you push the button, the if will fail.

This subroutine will be run as soon as Button1 is pressed. This will display two random numbers for the user to multiply. (Displayed in TB2 and TB3.)
Now, as soon as these numbers are displayed (and before the user has a chance to enter any answer) the program checks the value in TB4. This is empty, and throws an error when the parse is attempted.
Try breaking this into 2 subroutines with 2 buttons: one button to display a new problem, and one button to check the answer.
EDIT: Code added. (Note: I wrote this freehand--don't know if it would compile or not... just get the general idea. Note the button names.)
//This routine sets up the problem for the user.
private void btnGenerateProblem_Click(object sender, EventArgs e) {
//Get 2 random factors
int x = Randomnumber.Next(12);
int z = Randomnumber.Next(12);
//Display the two factors for the user
textBox2.Text = x.ToString();
textBox3.Text = z.ToString();
}
//This routine checks the user's answer, and updates the "correct count"
private void btnCheckAnswer_Click(object sender, EventArgs e) {
//Get the random numbers out of the text boxes to check the answer
int x = int.Parse(textBox2.Text);
int z = int.Parse(textBox3.Text);
//Compute the true product
int s = x * z;
//Does the true product match the user entered product?
if (s == int.Parse(textBox4.Text)) {
correct++;
numbercorrect.Text = correct.ToString();
}
}
Add verification code at the beginning of btnCheckAnswer_Click.

private void button1_Click(object sender, EventArgs e)
{
int result = Convert.ToInt32(textBox4.Text); int x, z;
if (Convert.ToInt32(textBox2.Text) * Convert.ToInt32(textBox3.Text) == result)
{
correct++;
numbercorrect.Text = correct.ToString();
Randomnumber.Next(12);
textBox2.Text = Randomnumber.Next(12).ToString();
textBox3.Text = Randomnumber.Next(12).ToString();
}
}

Related

Adding textbox value, stay high value

Goal: The value I enter in the first box will be written in the second box
Goal: The second textbox will always write the highest value even if the first textbox changes
private void ModuleltextBox_TextChanged(object sender, EventArgs e)
{
try{
secondTxt.Text = firstTxt.Text;
var y = int.Parse(secondTxt.Text);
var x = int.Parse(firstTxt.Text);
if (y >= x)
{
//??
}
else if(x<y)
{
//??
}
}
catch (Exception){
}
You just need to set the Text property after comparing both text boxes value like :
try
{
var y = int.Parse(secondTxt.Text);
var x = int.Parse(firstTxt.Text);
if (y < x)
{
secondTxt.Text = x.ToString();
}
else
{
secondTxt.Text = y.ToString();
// or probably this line is not needed as y is already set in second TextBox
}
if first text box value is greater it will get set in secondTextBox otherwise the secondTextBox already have highest value.
I would think something like this would suffice?
private void ModuleltextBox_TextChanged(object sender, EventArgs e)
{
int x, y;
if (int.TryParse(firstTxt.Text, out x) && int.TryParse(secondTxt.Text, out y))
{
secondTxt.Text = Math.Max(x, y).ToString();
}
}
Put this piece of code in your textbox1 TextChanged event.
try
{
textBox2.Text = textBox1.Text;
int firstnum = int.Parse(textBox1.Text);
int secondnum = int.Parse(textBox2.Text);
}
catch
{
}
I think your second goal is not possible if you're using a TextChanged event since every changes you'll made in TextBox1 will be also made in TextBox2.

Creating a meal Cost calculator C#

I'm trying to create a Meal Cost Calculator using C#.
Here is my current code
public partial class Form1 : Form
{
const double TAX_RATE = .076;
const double EXTRA_DISCOUNT = .1;
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void tiplistBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if ((lessThanButton.Checked == true) && (moreThanButton.Checked == false)) ;
{
int selectedIndex = tiplistBox1.SelectedIndex;
switch (selectedIndex)
{
case 1:
break;
}
}
}
private void calculateButton_Click(object sender, EventArgs e)
{
int mealCost = int.Parse(mealCostBox1.Text);
double tax = (mealCost * TAX_RATE) + mealCost;
double disc = (tax * EXTRA_DISCOUNT);
double tipRate = (tax - disc);
double totalCost = (tipRate);
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
int count = 1;
if ((lessThanButton.Checked == true) && (moreThanButton.Checked == false))
{
tiplistBox1.Items.Add("");
for (count = 10; count <= 35; count += 5)
tiplistBox1.Items.Add("Tip Rate: " + count + "%");
count++;
}
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
int count = 1;
if ((lessThanButton.Checked == false) && (moreThanButton.Checked == true))
{
tiplistBox1.Items.Add("");
for (count = 15; count <= 35; count += 5)
tiplistBox1.Items.Add("Tip Rate: " + count + "%");
count++;
}
}
}
The user must enter the amount of the meal.
Then the user selects a radio button that asks how many people ate. (one RB is for less than 6 and the other is for more than 6.) this button is used in order to give tip rates which are displayed in tiplistBox1 (if <6 ppl = 10,15,20,25,30,35, if >6 ppl 15,20,25,30,35) The user must also identify if there is any type of discount, which is selected from checking one of three boxes (student, military or senior) if either one is selected a 10% discount is added. Once all is selected the calculate button is supposed to take the mealCost add the TAX_RATE, take any discounts off and if a tip rate is selected from the tiplistBox1 options, add the tipRate then give the amount due.
Right now, my project isn't complete, there are a few issues, first of all, as you can see, I'm not using the If,Else statements, I'm required to use switch statements, when I'm running the program from the start I'm getting the tipRate's to display correctly for example, if I select the RB that is <6 people, then the tipRates shown are 10,15,20,25,30,35. If instead, from the start I select RB that is >6 people then the tipRates 15,20,25,30,35 are shown. That's good, but when I try to switch the RB within the ongoing program the TipRates get added underneath the first set of tipRates
, also since I'm using switch statements, if I select either of the RB, the displayed tipRates don't match up, meaning if I create a case 1: in one instance it shows 10% but in another is shows 15%, which messes with the calculation process.
I need help!
How can I ensure that the tipRate selected will make sence in the calculation.
for example if in case 1: it shows 15% but only does the math for 10% tipRate.
...but when I try to switch the RB within the ongoing program the TipRates get added underneath the first set of tipRates
That's because you need to clear the list before adding the new set of rates to the list.
Call tiplistBox1.Items.Clear() before calling tiplistBox1.Items.Add("").

Windows Form App Float to String

Below is some of my code that isn't working. I wanted to see it could count the number of spaces in the text box so I'm having it display the number in a message box and it currently just throws a blank one. The problem is either in the float to string conversion or in the counter.
private static string _globalVar = "n";
public static string GlobalVar
{
get { return _globalVar; }
set { _globalVar = value; }
}
public Form1()
{
InitializeComponent();
button1.Text = "Enter";
}
string LNum { get; set; }
public void button1_Click_1(object sender, EventArgs e)
{
MessageBox.Show(LNum);
}
public void richTextBox1_TextChanged(object sender, System.Windows.Forms.KeyEventArgs e)
{
float n = 0;
if (Control.ModifierKeys == Keys.Space)
{
n = n + 1; ;
}
string.Format("{0:N1}", n);
string LNum = Convert.ToString(n);
}
What you are doing is an excellent way to learn how and when the events are raised and how they can be leveraged to customize an applications behavior and is something similar to what many of us have done over the years.
Based on what you say you are wanting to do, there are several issues. If you take a look at this code, it will do what you want.
public void button1_Click(object sender, EventArgs e)
{
int n = 0;
for (int counter = 0; counter < richTextBox1.TextLength; counter++)
{
if (richTextBox1.Text[counter] == ' ')
{
n++;
}
}
MessageBox.Show(n.ToString("N1"));
}
The key difference is that I am only looking at the entered text when the button is clicked. (TextChanged is run every time there is a change in the text displayed). I chose not to use a float variable to store the count of spaces as the count will always be an integer.
In addition, the parameter to TextChanged System.Windows.Forms.KeyEventArgs e is incorrect and will never compile if correctly bound to the TextChanged event.
The KeyEventArgs parameter is used by the KeyUp and KeyDown events. If you use these events, you will be looking to count every time the space bar is pressed and not the number of spaces in the text box. And like their name suggests, the events are raised every time a Key on the keyboard goes Up (Pressed) and Down (Released).

Programming a windows form in a mature way

I am very new in C#. I have written a code to get two numbers in two text boxes and basically show their multiplication in a third text box.
The code is like:
private void button1_Click(object sender, EventArgs e)
{
double A = double.Parse(textBox2.Text);
double B = double.Parse(textBox3.Text); //gets the hourly wage
double C = A * B;
}
I have written them all in an executing button class. How can I get "A" and "B" in their own private texbox classes and relate them in "C" text box class?
I need to do it in order to validate the textboxes to give the user an error if he leaves any textboxes empty.
You may restrict user to fill in the text boxes before executing the button logic in this way:
private void button1_Click(object sender, EventArgs e)
{
if(textBox2.Text == string.Empty || textBox3.Text == string.Empty)
{
MessageBox.Show("Invalid input");
return;
}
double A = double.Parse(textBox2.Text);
double B = double.Parse(textBox3.Text); //gets the hourly wage
double C = A * B;
}
This is what u do to display your answer in the third textbox
private void button1_Click(object sender, EventArgs e)
{
if(textBox2.Text == string.Empty || textBox3.Text == string.Empty)
{
MessageBox.Show("Please Fill Both Text Box");
return;
}
double A = double.Parse(textBox2.Text);
double B = double.Parse(textBox3.Text);
textbox4.Text = (A * B).ToString();
}

c# winForm adding value to number in texbox

In my program i have several texboxes and buttons with coresponding names (ex. TextBox1 - buttonPlus1) like on the picture
but there are filled with numbers loaded from text file.
I want to write function that allows me to press button + and enlarge (add fixed number, for example 100) value from textbox. So far i have done:
private void buttonPlus1_Click(object sender, EventArgs e)
{
AddValue(sender,e);
}
private void AddValue(object sender, EventArgs e)
{
if (!(sender is Button))
return;
string controlName = (sender as Button).Name;
string textBoxName = controlName.Replace("buttonPlus", "textBox");
TextBox textBox = this.Controls.Find(textBoxName, false)[0] as TextBox;
int step = 100;
}
but i have no idea how to take value (as number) from textBox and add that step. Can somebody please help me? I tried to solve it by myself in many different ways, but it does not work
Get the value:
Convert.ToInt32(textBox.Text)
Save it to a variable, add 100 and just set it as usual.
P.S. You can also use Int32.Parse("")
textBox.Text = Convert.ToInt32(textBox.Text) + 100;
(You might need to .ToString() it)
EDIT:
As ltiong_sh mentioned, you should use TryParse rather then Parse:
int somevalue;
if(Int32.TryParse(textBox.Text, out somevalue))
{
textBox.Text = somevalue + 100;
}
You need to convert String to Integer
int txtValue = Convert.ToInt32(textBox.Text) + 100;
Make sure your validate the text in the text field. Else at the time of parsing it will throw an exception.
You can do this
int value = 0;
if(Int32.TryParse(textBox.Text, out value))
{
value += step;
textBox.Text = value.ToString();
}
else
{
//inform user to enter int
}
This is what you are looking for:
int newValue = Convert.ToInt32(textBox.Text) + step;
To put the value back in a textbox you can do the following:
textBox.Text = newValue.ToString();
Edit:
As mentioned by others you should use Int32.TryParse to prevent an error from being thrown.
if(Int32.TryParse(textBox.Text, out newValue))
{
newValue += step;
textBox.Text = newValue.ToString();
}
in button click get the textbox value and convert it to integer format and add 100 to it. after that reset textbox value to modified one's. Here is what you need.
private void buttonPlus1_Click(object sender, EventArgs e)
{
try
{
int txtValue = Convert.ToInt32(textBox.Text) + 100;
textBox.Text = txtValue.ToString();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}

Categories