I'm in my first semester of college, and we're doing C#. I have to make a Winforms app that can convert between Celsius and Fahrenheit. I have all the code down (basically), but I need to have the result output to a label. I can send the answer to the label with lblOutput = Output.ToString(); but I need a message like "[input] Celsius will is [output] Fahrenheit". I tried putting in between the brackets after "ToString" but I was getting an error.
I have everything else coded except for this. I have been looking for the last couple days to figure it out, but I can't find an answer. Any help is greatly appreciated.
Edit:
The code that I have set up appears inside of a button. I have two radio buttons that saying that the value put into a text box is either Far -> Cels or Cels -> Far.
This is what I have coded in my button. If there is any way to improve upon it, please let me know.
private void btnConvert_Click(object sender, EventArgs e)
{
decimal Input = Convert.ToDecimal(txtInput.Text); //grabs the input that the user entered
if (rbtnCelsius.Checked == true) //Test to see if the Celsius radio button is checked
{
decimal Output = ((Input - 32) * 5) / 9; //If yes, it uses this formula to convert the input from Farenheit to Celsius
txtOutput.Text = Output.ToString(); //Outputs the message to the user, showing the Celsius end point
}
else //Says that the Celsius Radio Button is not checked, meaning that the Farenheit radio button is
{
decimal Output = (Input * 9) / 5 + 32; //Moves onto this formula, converts Celsius to Farenheit
txtOutput.Text = Output.ToString(); //outputs the message to the user, showing the Farenheit end point
}
//txtOutput.Text = Output.ToString();
//Commented out because it gives an error saying that "Output does not exist in current context"
}
int fahrenheit, celsius;
// your code to set the two variables
string yourLabelText = String.Format("{0} Celcius is {1} Fahrenheit", celsius.ToString(), fahrenheit.ToString());
yourLabel.Text = yourLabelText;
Here is a reference for String.Format(). (thanks to Lukazoid!)
I don't know if you care about that, but for some cases you can get something like 12.243333333 by calling Output.ToString(), to make it more user-friendly, you can make it like this
Output.ToString("F2")
Which will change it to 12.24. You can use this together with string.Format like folks suggested.
I'm not sure what your question is about but if you need to format your output into a set phrase you can do this.
private void btnConvert_Click(object sender, EventArgs e)
{
decimal Input = Convert.ToDecimal(txtInput.Text); //grabs the input that the user entered
// declare this outside the loop so you can use it later.
decimal output = 0M;
if (rbtnCelsius.Checked == true) //Test to see if the Celsius radio button is checked
{
output= ((Input - 32) * 5) / 9; //If yes, it uses this formula to convert the input from Farenheit to Celsius
}
else //Says that the Celsius Radio Button is not checked, meaning that the Farenheit radio button is
{
output= (Input * 9) / 5 + 32; //Moves onto this formula, converts Celsius to Farenheit
}
txtOutput.Text =string.Format("{0} Celsius will is {1} Fahrenheit",input,output);
}`
p.s. Do remember to use a try parse method to ensure that the txtInput is definitely convertible to decimal.
you can use string.format to replace tokens like {0} or {1} in a string, or you can directly use string concatenation. I'd like to avoid directly giving you the answer since you said this is homework, but if you look for c# examples of this you should be able to find your way.
Related
I am building C# WinForms application which has 3 textboxes. First two take value and after calculation show value in third textbox. It has to be in textbox so user can change value if thinks that calculation is wrong. Everything works perfect, but when I run app on windows 7 I get huge error, it calculates that (for example ) 2 times 2.15 is 430. Why is that happening ? I tried installing latest .Net framework on that computer but still doesn't work and after research I have no further ideas.
num1 = num2 = sum = 0;
if (tbNum1.Text.Contains(","))
{
tbNum1.Text = tbNum1.Text.Replace(",", ".");
}
double.TryParse(tbNum1.Text, out num1);
if (tbNum2.Text.Contains(","))
{
tbNum2.Text = tbNum2.Text.Replace(",", ".");
}
double.TryParse(tbNum2.Text, out num2);
sum = num1 * num2;
sum = Math.Round(sum, 2);
tbSum.Text = sum.ToString();
Also, additional two problems appear with displaying WinForm.
First is that panels have different sizes and positions than I programatically set.
Secont is that ( and I suppose that is my fault because I am probably doing that wrong ) all panels show very slow. What I have is like 6 panels with particular dimensions and 6 buttons. Depending on pressed button, I set all panels visible to false and only correct panel visible to true. But it loads very slow. Do you have any suggestions ? Thanks a lot in advance !
Your parse to a double is wrong. You can do it like this:
double num1, num2, product = 0;
if (tb1.Text.IndexOf(",") != -1)
{
tb1.Text = tb1.Text.Replace(",", ".");
}
num1 = double.Parse(tb1.Text, System.Globalization.CultureInfo.InvariantCulture);
if(tb2.Text.IndexOf(",") != -1)
{
tb2.Text = tb2.Text.Replace(",", ".");
}
num2 = double.Parse(tb2.Text, System.Globalization.CultureInfo.InvariantCulture);
product = Math.Round(num1 * num2,2);
tb3.Text = product.ToString();
The character that double.Parse recognizes as the decimal separator depends on the supplied IFormatProvider; if you don't supply any, that's the one for the current culture.
If you specifically want to use the dot as the decimal separator, you can just use CultureInfo.InvariantCulture:
double.TryParse(tbNum2.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out double num);
I have a Textbox elements that I want to accept only byte values. Note that I'm pretty new to c#, so sorry if I'm missing something obvious.
so I have this piece of code
if (!byte.TryParse(last, out num) && last.Length > 1)
{
System.Media.SystemSounds.Asterisk.Play();
zBox.Text = zBox.Text.Remove(last.Length - 1);
}
So, what I want is for users to enter only byte values there, and anything else than numbers to be ignored (deleted and sound played indicating wrong input). The piece of code that is there achieves that with the problem of the first entered value which can be a letter. If I don't use .length > 1 than I get an expection.
What would be the best way to validate if the entered value is a byte type?
The problem is that you check for both conditions in your if statement, thus regardless of whether the first letter is byte or not, the checking will NOT succeed. Try something like:
byte num;
if (!byte.TryParse(last, out num))
{
System.Media.SystemSounds.Asterisk.Play();
if (last.Length > 1)
zBox.Text = zBox.Text.Remove(last.Length - 1);
else if (last.Length == 1)
zBox.Text = "";
}
EDIT after reading comment: added else if statement
You could handle the PreviewTextInput event:
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
TextBox tb = sender as TextBox;
string s = tb.Text + e.Text;
byte b;
if (!byte.TryParse(s, out b))
{
e.Handled = true;
//play sound
System.Media.SystemSounds.Asterisk.Play();
}
}
You may also want to handle the paste command:
Paste Event in a WPF TextBox
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I got 4 textboxes that I want to put values in, and I want it to find the average number from the values of the inputted values to the 4(or more) textboxes.
I want the average to display in a readonly box (is richtextbox good for this?).
You can use both a RichTextBox and normal TextBox for this. To ensure that it is read-only, in the designer page do the following;
Select the TextBox > Scroll under properties window > Behavior Section > Read-Only property
Setting this property to true will make the TextBox non-editable by the user.
After you have the 4 editable TextBoxes and 1 non-editable, you can implement something like the following to add up the numeric values of TextBoxes and display it in the readonly TextBox.
private void AverageAndDisplay()
{
try
{
//Convert values to numeric
decimal one = Convert.ToDecimal(textBox1.Text);
decimal two = Convert.ToDecimal(textBox2.Text);
decimal three = Convert.ToDecimal(textBox3.Text);
decimal four = Convert.ToDecimal(textBox4.Text);
//Find the average
decimal average = (one + two + three + four) / 4.0m;
//Show the average, after formatting the number as a two decimal string representation
textBox5.Text = string.Format("{0:0.00}", average);
}
catch(Exception e) //Converting to a number from a string can causes errors
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
}
So you should have this steps:
Create 4 textboxes. Let's this buttons has ID Value1Txt, Value2Txt, Value3Txt, Value4Txt
Add button with text Calculate Average Value. The ID of the button should be CalculateAverageBtn
Add the Label in which you will show the Average. The ID of this Label should be AverageValueLbl
Attach OnClick event on the CalculateAverageBtn. You could do it using the signature of the button OnClick="CalculateAverageBtn_Click" or doing it in the code
//this should be inside InitializeComponents method
CalculateAverageBtn.OnClick += CalculateAverageBtn_Click;
protected void CalculateAverageBtn_Click(object sender, EventArgs e)
{
//...code
}
Now in the body of CalculateAverageBtn_Click you should Parse the values of the TextBoxes and calculate the average. You could do this using decimal.TryParse method
decimal value1 = 0;
if(!decimal.TryParse(Value1Txt.Text, out value1)
{
//if you come in this if the parsing of the value is not successful so
you need to show error message to the user. This happen when the user
enters text like 123Test, this is not a number. So you need to show
error message
}
Create a label in which you will show the error message. Let's call it ErrorLbl. So when the parsing is not successful we will write in this label the error message.
if(!decimal.TryParse(Value1Txt.Text, out value1)
{
ErrorLbl.Text = "The value of value 1 textbox is not valid number"
return; //exit the button click method
}
Calculate the average of 4 textboxes and write it in the AverageValueLbl. This should be in button event click
AverageValueLbl.Text = (value1+value2+value3+valu4)/4.ToString();
Try to understand what you are doing, don't copy/paste mindlessly code. This is pretty much beginner programming. For sure this is homework, so try to understand it because in the future harder homeworks you will be lost.
I am trying to create a form that will convert Celsius to Fahrenheit and vice versa, but I am running into an error with the Conversion buttons code. The problem I am getting is that the variable convertedTemperature is left empty, so that should validation fail the message will be displayed via the ouput label(lblConvertedTemperature). But because of this being left blank I get the use of unassigned variable error. My question is how can I reword the processing section to not cause this error.
Double inputTemperature;// the variable that will store txtTemperatureInput for calculation
Double convertedTemperature;// the variable that will store the converted temperature
/*********************************
* INPUT *
* *******************************/
// when the user inputs a value and clicks calculate, the input must first be validated
if (Double.TryParse(txtTemperatureInput.Text, out inputTemperature) == false)
{
lblConvertedTemperature.Text = "Temperature must be a numeric value.";// message displayed in
//output label telling user their input was not accepted because it was not numeric
txtTemperatureInput.Focus();// sets the focus back onto the temperature textbox for a new entry
}
else
{
/*******************************
* PROCESSING *
*******************************/
if (optConvertToCelsius.Checked == true)// if the convert to celsius radio button is selected
// this statement will run
{
convertedTemperature = (inputTemperature - 32)*5 / 9;// the formula for converting
//Fahrenheit to Celsius
}
else if (optConvertToFahrenheit.Checked == true)// convert to fahrenheit was selected,
//meaning the convert to fahrenheit radio button was selected, so this statement will run
{
convertedTemperature = (inputTemperature * 9) / 5 + 32; ;// the formula for converting Celsius to
//Fahrenheit
}//end concatonated if
}//end if
/******************************
*OUTPUT *
******************************/
lblConvertedTemperature.Text = Math.Round(convertedTemperature, 4).ToString();// sets the converted temperature
// label to the value of convertedTemperature
}
}
}
My question is how can I reword the processing section to not cause this error.
Well, there are two situations that the compiler is concerned about:
If the input is invalid, you're already changing lblConvertedTemperature.Text anyway... so just return after you've done that. (You then don't need an else clause, which means you'll have less nesting - always nice for readability.)
Neither optConvertToCelsius nor optConvertToFahrenheit is checked. That's a situation the compiler considers, because you've got two separate conditions that you're checking. You may know it's never going to happen, of course.
For the latter, I'd suggest just removing the second condition:
if (optConvertToCelsius.Checked)
{
...
}
else
{
...
}
Note that I've removed the == true from the first condition just as a matter of style.
Now the compiler will know that if you get to this point, one of those two blocks will be executed. As both blocks assign to convertedTemperature, the variable will be definitely assigned at the end of that code.
EDIT: Just to clarify, if you have:
if (someCondition)
{
...
}
else if (someOtherCondition)
{
...
}
the compiler will not assume that one of those blocks will be executed, regardless of what the conditions are. Even if you know that exactly one condition will be true, the compiler just follows its relatively-simple rules.
You're scoping looks off. Simply move
/******************************
*OUTPUT *
******************************/
lblConvertedTemperature.Text = Math.Round(convertedTemperature, 4).ToString();// sets the converted temperature
// label to the value of convertedTemperature
To the "processing" scope.
I'm developing a calculator in C# and I have a button that inserts a decimal point into the number. I ran into a problem where it allows the user to insert multiple decimal points into the interface, which threw everything off. I cooked up this little statement:
if ((number % 1) > 0)
{
richTextBox1.Text = richTextBox1.Text + "";
}
else
{
richTextBox1.Text = richTextBox1.Text + ".";
}
Except it doesn't do anything! Will someone please show me a way to only allow one decimal point by fixing this statement?
onButtonToInsertDecimalClick
if richTextBox1.Text.Contains(".")
return;
else
... rest of code
Wouldn't this (pseudocode) work?
Have you tried using Double.TryParse directly?
if(Double.TryParse(richTextBox1.Text, myDoubleValue) == false)
richTextBox1.Text = lastGoodValue;
else
lastGoodValue = richTextBox1.Text;
this will also, via TryParse, give your actual double variable the proper result. As long as this occurs every time richTextBox1.Text changes, the correction code should also cause the double value to remain good, since it'll trigger when Text is reverted to lastGoodValue.