Event Handlers in My Converter App Are Not Working - c#

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.

Related

C# form/gui need to utilize combination of user input and combo box drop down to get result

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

Creating decreasing sequence with (x++)%n in C#

So, I know that with a code snippet such as:
int x = 0; //class field variable
private void button1_Click(object sender, EventArgs e)
{
Label1.Text += (x++)%4 + 1;
}
a sequence of 12341234 is displayed on the form if the button is clicked 8 times.
My goal is to get 43214321 to display.
I'm able to get 32103210 with:
int x = 0; //class field variable
private void button1_Click(object sender, EventArgs e)
{
Label1.Text += 3-(x++)%4;
}
I'm also able to get 32143214 with:
int x = 1; //class field variable
private void button1_Click(object sender, EventArgs e)
{
Label1.Text += 4-(x++)%4 + ;
}
What am I doing wrong? And is there a general formula for this?
Note: My x DOES have to be initialized to 1.
Just change the formula to:
Label1.Text += 4-((x-1)++)%4;
Try using this formula:
5-(1+(x+++3)%4)
That is:
Label1.Text += (5-(1+(x+++3)%4)).ToString();
The first line of code that you've written is basically cycling between 3 to 1.
x=0;
Label1.Text += 3-(x++)%4;
x=0 || Output=3.
Label1.Text= 0+3-(0%4)=3
x=1 || Output=2.
Label1.Text= 0+3-(1%4)=2
x=2 || Output=1.
(Dry run as done above)
x=3 || Output=0.
(dry run as done above)
x=4 and the cycle repeats.
You could dry run your second line of code to understand why your answer comes the way it does, but to answer your question in concise:
int x = 0; //class field variable
private void button1_Click(object sender, EventArgs e)
{
Label1.Text += 4-(x++)%4;
}

winforms leave event and textchanged

I'm new to learning winforms and i'm stuck on the following problem and I do not think what I have done is the correct way, so any help would be appreciated.
I have 4 textboxes such as the following
private void txtBxPlayer1Bid_TextChanged(object sender, EventArgs e)
{
txtBxFundsAvialable.Text = (Convert.ToInt32(txtBxFundsAvialable.Text) - Convert.ToInt32(txtBxPlayer1Bid.Text)).ToString();
}
The 5th textbox txtBxFundsAvialable simple subtract the value of txtBxPlayer1Bid from txtBxFundsAvialable.
In designer.cs I have
this.txtBxPlayer1Bid.Leave += new System.EventHandler(this.txtBxPlayer1Bid_TextChanged);
The problem I have is, if I have 100 in txtBxFundsAvialable and enter 10 in txtBxPlayer1Bid the value in txtBxFundsAvialable should be 90, but txtBxPlayer1Bid etc seem to go into a loop and the value in txtBxFundsAvialable becomes 60. 4 textboxes X 10.
This happens for any of the 4 textboxes
The only way I can solve the problem is to set the values of the 4 textboxes to 0 in the txtBxFundsAvialable_TextChanged as shown below.
private void txtBxFundsAvialable_TextChanged(object sender, EventArgs e)
{
if (Convert.ToInt32(txtBxPlayer1Bid.Text) > 4 || (Convert.ToInt32(txtBxPlayer2Bid.Text)> 4 || (Convert.ToInt32(txtBxPlayer3Bid.Text)> 4) || (Convert.ToInt32(txtBxPlayer2Bid.Text)> 4)))
{
txtBxPlayer1Bid.Text = "0";
txtBxPlayer2Bid.Text = "0";
txtBxPlayer3Bid.Text = "0";
txtBxPlayer4Bid.Text = "0";
}
}
Is what I'm doing the correct way, as stated at the beginning, I'm new to winforms and it a canny leanning curve
I wrote a simple code with 2 textboxes that get values and a textbox with the result. Updates with TextChangedevent. Try to use it to fix your code..
private void textBox1_TextChanged(object sender, EventArgs e)
{
try
{
int num1 = Int32.Parse(textBox1.Text), num2 = Int32.Parse(textBox2.Text);
textBox3.Text = (num1 - num2).ToString();
}
catch { }
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
textBox1_TextChanged(sender, e);
}
EDIT
Try this code and link any of your "bid" textboxes to this function. textbox1 in this code is equivalent to your "available" textbox.
private void textBox_Leave(object sender, EventArgs e)
{
try
{
int num = Int32.Parse(((TextBox)sender).Text), available = Int32.Parse(textBox1.Text);
textBox1.Text = (available - num).ToString();
}
catch { }
}
Not sure how .Leave operates. Try to use .TextChanged or whatever the equivalent in WinForms.
All four (or even five) text boxes should use same event callback method.
Here is what you can do in that method:
private void txtBx_TextChanged(object sender, EventArgs e)
{
double player1 = 0, player2 = 0, player3 = 0, player4 = 0, total = 0;
if (int.TryParse(txtBxPlayer1Bid.Text, out player1)
&& int.TryParse(txtBxPlayer2Bid.Text, out player2)
&& int.TryParse(txtBxPlayer3Bid.Text, out player3)
&& int.TryParse(txtBxPlayer4Bid.Text, out player4)
&& int.TryParse(txtBxFundsAvialable.Text, out total)
{
total = player1 + player2 + player3 + player4;
}
}

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# Calculator typing by pressing buttons

I am studying C# now, so i am making some kind of exercises to get used to C# syntax and learn better. I decided to make a calculator looking alike the normal windows calculator.
I created only one button "1" and one textbox.
I want to make this button write 1 in textbox when I press it and also make an int variable equal to the number in the textbook, to make the calculation later. So I can't either change "int a"'s value or change text in the textbox, it always shows 01, because a always equals to 0.
How can I make the program, both show the correct numbers and change the value of a correctly?
For example how can i make the program show eleven in the textbox when i press button twice and also change "int a"'s value to 11?
public partial class Form1 : Form
{
int a;
string Sa;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Sa = a.ToString() + "1";
textBox1.Text = Sa;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text += "1";
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
a = Int32.Parse(textBox1.Text);
}
just it.. Change text on textBox every button click, and change variable a every textBox changed.
The value could then be set using
a = int.Parse(Sa);
textBox1.Text = Sa.TrimStart('0');
Although if you'd like to be more efficient about it,
a = a * 10 + 1;
not have Sa at all,
textBox1.Text = a.ToString();
If you run into integer overflows, you should use BigInteger.
You have several options:
Make int a nullable int. That way you can check if int is already set
int? a;
if ( a.HasValue )
{
}
else
{
}
Check if the Text property of textBox1 is empty (which means you don't have to append a to it)
if ( textBox1.Text == string.Empty)
{
}
else
{
}
public void btnOne_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnOne.Text;
}
private void btnTwo_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnTwo.Text;
}
// etc
for any button you want to append text to the text box set the click property to btn_Click then pt this code inside the method
private void btn_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
// This will assign btn with the properties of the button clicked
txt_display.Text = txt_display.Text + btn.Text;
// this will append to the textbox with whatever text value the button holds
}

Categories