Event Handlers in My Converter App Are Not Working
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 i开发者_开发技巧t 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.
精彩评论