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();
}
Related
I have a GUI that is using a text field for a user int input.
a combo box that has drop downs for calculations (sum, add, div, mult. etc.)
then I click a button to calculate.
the Results show in bottom text field.
I am having trouble getting the combobox to string, so that I can make the right calculation.
The first part also needs the combobox to be selected on "Initialize" to add the value to the result text field. After that is added, all combobox choices after will utilize the initialized value in the results field and the user input field for any function calls.
namespace GUI
{
public partial class Form1 : Form
{
static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
}
public Form1()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string path = #"C:\Users\calculations.txt";
StreamReader sr = new StreamReader(path);
string x = sr.ReadToEnd();
string[] y = x.Split('\n');
for (int i = 0; i < y.Length; i++)
{
comboBox1.Items.Add(y[i]);
}
}
//Button to calculate Resualt
private void button1_Click(object sender, EventArgs e)
{
string x = comboBox1.SelectedItem.ToString();
int b = int.Parse(textBox2.Text);
if(x == "Initialize")
textBox1.Text = (b).ToString();
else if (textBox1 == null)
Console.WriteLine("Please Initialize value");
if(x == "Sum")
textBox1.Text = (b + b).ToString();
}
//Result text box
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
//User number input box
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
}
}
Values in calculation.txt
Initialize
Sum
Subtract
Product
Power
Log
private void submitbutton_Click(object sender, EventArgs e)
{
if (fishingrodcomboBox.SelectedIndex == 2)
{
fishingrodcomboBox.SelectedIndex = 2;
decimal two = 18m;
decimal price = two * fishingrodnumericUpDown.Value;
totalfishingrodtextBox.Text = price.ToString("C");
}
else
{
//Do something
}
}
Textbox doesnt display the amount and how i do code it such that when i select something from the combo box i can each a different value?
How can i make auto refresh textbox while typing value like this?
i tried to do the same but it did not work. i always to hit ENTER to refresh or click on up/down arrows to refresh the value
here is the code
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
try
{
double a = double.Parse(s1.Text); //textbox 1
double b = double.Parse(s2.Text); //textbox 2
double s = a * b;
resultSpeed.Text = "" + s; //s is the result
}
catch
{
MessageBox.Show("Please input the number");
}
}
Just use event KeyUp. It will trigger every time you put a symbol.
ValueChanged isn't working because it only triggers when you are done with editing - you press enter or change focus.
So basically change your event from ValueChanged to KeyUp.
I'm not posting any code because the only change will be subcribing to other event. Your function is fine, however you should change its name :)
Put your code into textbox's TextChanged Event.
Like this
private void textBox1_TextChanged(object sender, EventArgs e)
{
calculate();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
calculate();
}
private void calculate()
{
double a = 0, b = 0, demo;
if (double.TryParse(textBox1.Text, out demo))
a = double.Parse(textBox1.Text); //textbox 1
if (double.TryParse(textBox2.Text, out demo))
b = double.Parse(textBox2.Text); //textbox 2
double s = a * b;
textBox3.Text = s.ToString(); //s is the result
}
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();
}
}
This is the code I have so far:
public partial class Form2 : Form
{
public Double X;
public Form2()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
if(textBox1.Text != "")
X = Convert.ToDouble(textBox1.Text);
X *= 0.001;
label3.Text = "metros";
}
private void button3_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
X = Convert.ToDouble(textBox1.Text);
X *= 0.62;
label3.Text = "milhas";
}
private void button4_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
X = Convert.ToDouble(textBox1.Text);
label3.Text = "quilómetros";
}
private void button5_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
X = Convert.ToDouble(textBox1.Text);
X *= 3280,84;
label3.Text = "pés";
}
private void button6_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
X = Convert.ToDouble(textBox1.Text);
X *= 0.17998560115190784737;
label3.Text = "léguas";
}
private void button1_Click(object sender, EventArgs e)
{
textBox2.Text = Convert.ToString(X);
}
This is how the window looks like:
What these do is, when you insert a value on textBox1 (the red one on the middle left of the window), you then select the measurement from the buttons on the right, this will convert the introduced value to kilometres and store it in the variable X and write the chosen measurment on a label to the right of the textBox1.
When you press the "Converter" button, (for now) I wanted the textBox2 to show X, however, this only works when I press "metros" or "pés", if I choose one of the other buttons for the conversion it will simply do nothing...
Does someone have any idea of what's wrong?
And also, side question, how do you select items from the comboBox?
Firstly, if statements only execute the very next statement if their condition is met:
if(textBox1.Text != "")
X = Convert.ToDouble(textBox1.Text); // only run if 'if' is true
X *= 0.001; // always run
label3.Text = "metros"; // always run
The if is associated with the next line. If you want all of the following code to be associated with the if, then you need to open a block:
if(textBox1.Text != "")
{
X = Convert.ToDouble(textBox1.Text);
X *= 0.001;
label3.Text = "metros";
}
To help guard against this, I would advise adopting a consistent style for single-line if statements:
if (something) SomeStatement(); // same line
if (something)
SomeStatement(); // indented
if (something)
{
SomeStatement(); // single statement block
}
It's possible some of your buttons are not working because the link between the event handler methods and the events has been broken. You should open the designer and ensure that each of the buttons has a Click handler assigned.
With respect to the combo-box part of your question: ComboBox.SelectedItem allows you to get or set the selected item. Alternatively you can use ComboBox.SelectedIndex to get or set the index of the item that is selected.