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);
}
}
Related
I am creating a C# application that generates two random integers,between 100 to 500. The numbers should perform addition such that
247 + 129 = ?
The form has a text box for the user to enter the problem's answer. When a button is clicked, the application should do the following:
Check the user's input and display a message indicating whether it is the correct answer or not.
Generate two new random numbers and display them in a new problem on the form
add a button named "Save score to file".
When clicked, this button should write the total number of problems, the number of correct answers as well as the percentage of problems answered correctly.
Code:
InitializeComponent();
Random rand = new Random();
{
int number1;
number1 = rand.Next(400) + 100;
numberLabel1.Text = Convert.ToString(number1);
}
{
int number2;
number2 = rand.Next(400) + 100;
numberLabel2.Text = Convert.ToString(number2);
}
}
private void checkButton_Click(object sender, EventArgs e)
{
int correctAnswer;
correctAnswer = int.Parse(numberLabel1.Text) + int.Parse(numberLabel2.Text);
int userAnswer;
userAnswer = Convert.ToInt32(userInputBox.Text);
if (userAnswer == correctAnswer)
{
MessageBox.Show("Your Answer is Correct");
}
else
{
MessageBox.Show("Your Answer is Incorrect");
}
}
private void clearButton_Click(object sender, EventArgs e)
{
numberLabel1.Text = "";
numberLabel2.Text = "";
userInputBox.Text = "";
}
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void answerBox_TextChanged(object sender, EventArgs e)
{
}
}
}
The question I have is: How do I get an output? The message box isn't showing and I answer the problem correctly each time. After This how do Generate two new random numbers and display them in a new problem on the form add a button named "Save score to file".
When clicked, this button should write the total number of problems, the number of correct answers as well as the percentage of problems answered correctly.
private static Random rand = new Random();
private void checkButton_Click(object sender, EventArgs e)
{
int num1 = rand.Next(400) + 100;
int num2 = rand.Next(400) + 100;
label1.Text = num1.ToString();
label2.Text = num2.ToString();
int correctAnswer = num1 + num2;
int userAnswer = Convert.ToInt32(textBox1.Text);
if (userAnswer == correctAnswer)
{
MessageBox.Show("Your Answer is Correct");
}
else
{
MessageBox.Show("Your Answer is Incorrect");
}
}
[First]
Console.WriteLine ( String.Format("Answer => " + userAnswer ) );
will show it on console window
MessgeBox.Show( ( String.Format("Answer => {0}", userAnswer ) );
will show it on MessageBox.
I put 2 types of how to use String.Format for you :)
[Second]
you can make a button which do the task again.
put your generating code under the button function
[Third]
You need to study about StreamWriter
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;
i have textbox on a windows form and i want to be insert only numbers in this textbox.i use the following c# code for that
private void ChildAge_TextChanged(object sender, EventArgs e)
{
int i;
if (!int.TryParse(ChildAge.Text, out i))
{
MessageBox.Show("Plaese enter a valid Age");
}
}
it is working, but the problem is that , after showing the Message, when i Backspace the content and text box become null, on that situation also this message box shows again.
Do a little test like bellow:
int i = 0;
if(!string.IsNullOrEmpty(ChildAge.Text) &&
!int.TryParse(ChildAge.Text, out i)
)
{
MessageBox.Show("Enter Valid Age");
}
Try Using Below. This works better.
bool m_BackPressed = false;
private void ChildAge_TextChanged(object sender, EventArgs e)
{
int i;
if (!m_BackPressed)
{
if (!int.TryParse(ChildAge.Text, out i))
{
MessageBox.Show("Plaese enter a valid Age");
}
}
}
private void ChildAge_KeyPress(object sender, KeyPressEventArgs e)
{
m_BackPressed = (e.KeyChar.Equals((char)Keys.Back)) ? true : false;
}
I made a simple application to add 2 numbers together but when I add two letters together or a invalid sign it crashes the program. How do I create a message box showing something saying "please put in a number" when someone inserts a letter
Here's my code:
public partial class frmAdd : Form
{
string first;
string second;
public frmAdd()
{
InitializeComponent();
}
private void btnFirst_Click(object sender, EventArgs e)
{
first = txtNumber.Text;
}
private void btnSecond_Click(object sender, EventArgs e)
{
second = txtNumber.Text;
}
private void btnResult_Click(object sender, EventArgs e)
{
int a = Convert.ToInt32(first);
int b = Convert.ToInt32(second);
int c = a + b;
txtResult.Text = c.ToString();
}
}
Use TryParse instead:
private void btnResult_Click(object sender, EventArgs e)
{
int a, b;
if (int.TryParse(first, out a) && int.TryParse(second, out b))
{
int c = a + b;
txtResult.Text = c.ToString();
}
else
{
MessageBox.Show("Invalid Input!");
}
}
Or perhaps a better method would be to trap the error when the user first inputs the data:
public partial class frmAdd : Form
{
int first; // changed to int
int second;
private void btnFirst_Click(object sender, EventArgs e)
{
if (!int.TryParse(txtNumber.Text, out this.first))
{
MessageBox.Show("Invalid Input!");
}
}
private void btnSecond_Click(object sender, EventArgs e)
{
if (!int.TryParse(txtNumber.Text, out this.second))
{
MessageBox.Show("Invalid Input!");
}
}
private void btnResult_Click(object sender, EventArgs e)
{
int c = first + second;
txtResult.Text = c.ToString();
}
}
You can use NumericUpDown control instead of TextBox - it will not allow user to input invalid data.
Or you can add validation to TextBox value after user entered something. Add ErrorProvider to your form. And subscribe to Validating event of txtNumber textbox. This event will occur when textbox loses focus. If entered text is not an integer, then error will be shown near texbox, and your button will not be clicked:
private void txtNumber_Validating(object sender, CancelEventArgs e)
{
int value;
if (!Int32.TryParse(txtNumber.Text, out value))
{
errorProvider1.SetError(txtNumber, "Value is not an integer");
return;
}
errorProvider1.SetError(txtNumber, "");
first = value; // it's better to save integer value than text
}
Validation looks like:
You can add a bit of validation to check if you can create an int from the string value passed in.
int.TryParse is a simple way of doing this.
And for the MessageBox you can just use the MessageBox calss
Example:
private void btnResult_Click(object sender, EventArgs e)
{
int a = 0;
int b = 0;
if (!int.TryParse(first, out a))
{
MessageBox.Show("first is not a number");
return;
}
if (!int.TryParse(second, out b))
{
MessageBox.Show("second is not a number");
return;
}
int c = a + b;
txtResult.Text = c.ToString();
}
Instead of using Convert.ToInt32(string), you might actually use Int32.tryParse(String, out int), as shown below:
int a, b;
a = Int32.tryParse(first, out a);
b = Int32.tryParse(second, out b);
If the conversion fails, the tryParse method will result in a zero. If it succeeds, it will give you the number which is to be found in the string.
Hope it helped you out, had to find this too in my first few days of C#.
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.