I have a textblock, a button and a textbox.
What I want is the user enter data in a textbox (only numbers - whole numbers or decimals) and press the button appears on the textblock the result of an operation (multiplication) based on the value that the user entered.
For exemple (Button Click Event)
int num = TextBox.Text;
TextBlock.Text = num * 0.02;
What I want is: the user enters in the TextBox a decimal or integer (eg 50), when you press the button want to appear in the TextBlock the value that the user entered * 0.02. The result to appear is 1
First, you will need to parse the string
you can use the int num = Int.Parse(TextBox.Text) method
Just don't forget to validate the TextBox so it contains only numbers
C# is a type safe language, so you can't calculate "hello" (string) * 1 (int).
So you have to parse the string into the correct type. Because you not only need whole numbers, you have to choose between decimal and double.
Also the user can enter an invalid number, so better to check the Input.
This will look like:
const decimal multiplicator = 0.02;
double number;
if (Double.TryParse(TextBox.Text, out number))
{
var result = number * multiplicator;
//do what you want with the result ;)
}else
{
//TextBox.Text is not a valid number!
}
Related
I'm attempting to create a wpf app that takes a list of numerical values, separated by line breaks, in one textbox. You click a button, and it outputs the new numerical values into a second textbox. I'm running into issues separating the values the user inputs.
For this to make more sense the first textbox is called inputBox and the second textbox is called outputBox. The button will have event mathClick. We will have the button just multiply the number by 2.
This is what I have:
private void mathClick(object sender, RoutedEventArgs e)
{
foreach (var num in inputBox.Text.Split("\n"))
{
if(double.TryParse(num, out double value))
{
outputBox.Text = Convert.ToString(value * 2);
}
}
}
This is what happens
inputBox:
7.02
18.98
3.51
outputBox:
7.02
It's only grabbing the last value in the textbox and doing the arithmetic on that.
This is the scenario I'm trying to achieve
inputBox:
7.02
18.98
3.51
outputBox:
14.04
37.96
7.02
Any help is greatly appreciated.
I figured it out, if any other beginners like me come across this - you must remember Textbox will return a string. The way I fixed it was to split the input at the linebreak and store it in a string array
string[] stringNum = textbox.text.split("\n");
Then you can use a for loop to convert this array of type string to a double and print the double to your textbox with a linebreak each time the loop runs.
for (int i = 0; i < stringNum.Length; i++)
{
double num = Convert.ToDouble(stringNum[i]);
textbox.text += Convert.ToString($"{num}\n");
}
Hope this helps someone else, thanks.
Quick question how do I use same variable for string input in case and int input in another case. Here is what I mean by that, I have a problem where I need to constantly insert number and then put the addition of those numbers inside another variable. This inserting is inside do while loop, for me to exit the loop and to show the sum of those numbers, I need to type "OK" or "ok". I have a problem where I do not know how to use string variable for int inputs.
Here is my code:
string input= "";
int sum = 0;
do
{
Console.WriteLine("Insert the number or OK (ok) for exit: ");
input = Console.ReadLine();
sum += Convert.ToInt32(input);
// this is where I get the error Input string was not in the correct fromat
} while (input != "OK" && input != "ok");
Console.WriteLine(sum)
If anyone knows how to help me with this, I would gladly appreciate it.
First identify that the user entered integer or not using int.TryParse(), if user entered integer then add it to the sum variable otherwise check the string
do
{
Console.WriteLine("Insert the number or OK (ok) for exit: ");
input = Console.ReadLine();
//This will add number only if user enters integer.
if(int.TryParse(input, out int number)
sum += number
} while (input != "OK" && input != "ok");
You have to test for OK before you try to convert to a number, because OK won't convert to a number
string input= "";
int sum = 0;
while(true)
{
Console.WriteLine("Insert the number or OK (ok) for exit: ");
input = Console.ReadLine();
if("OK".Equals(input, StringComparison.OrdinalIgnoreCase)) //do a case insensitive check. Note that it's acceptable to call methods on constants, and doing a string check this way round cannot throw a NullReferenceException
break;//exit the loop
sum += Convert.ToInt32(input);
}
Console.WriteLine(sum);
You'll still get the error if the user enters input other than OK, that is not convertible to a number, but this is the crux of your current problem. I'll leave dealing with other garbages as an exercise for you...
This question already has answers here:
How do I get a TextBox to only accept numeric input in WPF?
(33 answers)
Closed 2 years ago.
i have tried looking for some scources on how to make the user only enter numbers instead of letters. i want to display a message on that so the user knows they need to type in a number. i would like some pointers on how to impliment that condition.
(this is done in WPF c# visual studio)
private void Add_Click(object sender, RoutedEventArgs e)
{
//text box
number1 = Convert.ToInt32(TextBox1.Text);
number2 = Convert.ToInt32(TextBox2.Text);
//if number1 and number2 are less than 1
if (number1 < 1 || number2 < 1|| number1 > 100 || number2 > 100)
{
MessageBox.Show("INVALID INPUT");
TextBox1.Text = " ";
TextBox2.Text = " ";
}
else if (!success)
{
MessageBox.Show("Type a number please.");
success = int.TryParse(TextBox1.Text, out number1);
success = int.TryParse(TextBox2.Text, out number2);
}
//operation
answer = number1 + number2;
//
//when clicked
answerText.Text = answer.ToString();
}`
You are going about it the wrong way. In WPF, you can do "binding" to a public getter/setter of a given type. The framework itself does the converting and allows proper value or not without you having to try and parse it.
For example, in your code-behind (.cs portion), create a public property for what you are using for input. Ex:
// This is a public getter/setter for binding and defaults its value to 27.
public int MyTextInput {get; set; } = 27;
The only reason I am setting the default to 27 is so when you get the binding done and run the form, you know it is working properly if the form shows 27 when initially displayed. If not, then your binding / data context is not correct and have to fix that part first. But once its done, you should be good and can change the default back to 0.
Then, in the single textbox on the form wide enough to show 2 digits, set the binding to this property something like (you may need to specify a grid row/column if your form is so established with a grid for alignment).
<TextBox Text="{Binding MyTextInput}" MaxLength="2" />
Now, when you run the form, the textbox control will be "bound" to your class's public property "MyTextInput" as an integer data type. If you try to put in charaacters, wpf will automatically show the box with a red border indicating an invalid value.
Then, in whatever your click / button handler is, you can just look at the "MyTextInput" value and go accordingly.
Obviously if you have multiple actual values you are expecting, just create two public properties and two textbox entries each bound to a respective public property you make available.
so i have 2 labels. one of them is a fixed number and doesn't change but the other one changes every 5 seconds. Now i want to multiply them automatically and show them in another label as Results.
what should i do? what am i doing wrong?
i tried this code but it says "operator * cannot be applied to string and string".
label1.Text = BTC_A.Text * BTCPrice_Label.Text;
then i tried
double txt1 = Convert.ToDouble(BTC_A.Text);
double txt2 = Convert.ToDouble(BTCPrice_Label.Text);
double sum = txt1 * txt2;
label1.Text = sum.ToString();
but it says "Input string was not in a correct format"
Think it through step by step.
You have labels with a Text property. That property is of type string. C# is a strongly typed language: strings can not be multiplied like that. In the end, a label can be empty, or the user could input any random string. What would be the result of "foo" * "bar"?
Also, when you do have a double as a result of some multiplication, you want to show it to the user in another label.Text. Here you have the inverse issue: C#/.Net does not convert the variable of type double implicitly to a string.
So you will have to
check if the strings entered by the user is actually a valid double
if they are, convert those strings to double and multiply them
convert the result to a string, and assign it to the labels Text property
if the strings are not valid numbers, leave the label empty, or show some other message
The logic to achieve this would be something like this:
var validPrice = int.TryParse(BTCPrice_Label.Text, out double price);
var validAmount = int.TryParse(BTCA_Label.Text, out double amount);
if (validPrice && validAmount)
{
var result = price * amount;
label1.Text = result.ToString();
}
else
{
label1.Text = "something is wrong";
}
so the problem was a dollar sign ( $ ) that i put before the numbers.
i just deleted the sign and this is what the code looks like now:
double AA;
if (!double.TryParse(BTC_A.Text, out AA))
{
MessageBox.Show($"Unable to convert the BTC_A \"{BTC_A.Text}\" to a floating point number");
return;
}
double btcA;
if (!double.TryParse(BTCPrice_Label.Text, out btcA))
{
MessageBox.Show($"Unable to convert the price \"{BTCPrice_Label.Text}\" to a floating point number");
return;
}
label1.Text = (AA * btcA).ToString();
This question already has answers here:
Empty String to Double C#
(5 answers)
Closed 6 years ago.
My program lets you choose the product, number of items from a combobox and lets you write the price in a textbox and it will calculate the amount (number of items * price), the 30% discount and the price after discount.
If every box is filled it won't show error, but if I leave the number of items combobox and/or price empty I get this error:
Exception thrown: 'System.FormatException' in mscorlib.dll
Additional information: Input string was not in a correct format.
And it will highlight this line: price = double.Parse(textBox1.Text);
private void button1_Click(object sender, EventArgs e)
{
double amount, price, dis,
itemnum = double.Parse(comboBox2.Text),
disrate = 30.0, totalafterdis;
price = double.Parse(textBox1.Text);
amount = price * itemnum;
dis = amount * (disrate / 100);
totalafterdis = amount - dis;
textBox2.Text = amount.ToString();
textBox3.Text = dis.ToString();
textBox4.Text = totalafterdis.ToString();
}
I am not really familiar with C#, so I'm not sure if it's a rookie mistake or not.
If you left the textBox1 empty, you would get this error. This exception is basically telling you that, the value you have entered, is not in a suitable format for parsing to type double.
Here is an example. You will not/can not be able to parse, for instance, the value "hello", to a type double. Your program at the moment is trying to parse an empty/null value to a double, which is not valid.
You should make use of the TryParse function, as below:
double result = 0;
bool isValidDouble = double.TryParse(textBox1.Text, out result);
//logical code here to check value of result
This will not throw an exception if your value of your textBox1 is invalid for parsing.
If you don't insert anything then it presents an empty string, which cannot be converted to an integer so try this:
double temp;
if(double.TryParse(textBox1.Text, out temp)){
price = double.Parse(textBox1.Text);
}