I have an application with four text boxes. I want user to be able to enter a value in the first three text boxes. The fourth will give the result (box1 + box2 + box3) / 3.
My textboxes look like this.
private void rBox_1_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
CheckIsNumber(e);
}
And a function to let user enter only digits.
private void CheckIsNumber (TextCompositionEventArgs e)
{
int result;
if (!int.TryParse(e.Text, out result))
{
e.Handled = true;
}
}
The problem is I don't know how to convert and store a value from each textbox in an int.
I've created a null int value to store. In public MainWindow().
int box1_value;
And for function I did this.
public static int GetNumber (string arg)
{
int number = Int32.Parse(arg);
return number;
}
When I'm trying to apply this function this way, nothing happens. Program won't start, no errors, though.
public MainWindow()
{
InitializeComponent();
int box1_value = GetNumber(rBox_1.Text);
}
Remove the
int box1_value = GetNumber(rBox_1.Text);
from your mainwindow constructor.
You're parsing a string.Empty value to int in which the compiler will automatically halt during compilation. Hence your awkward error.
Create a new function called Calculate for calculating your values
private void Calculate()
{
if(string.IsNullOrEmpty(rBox_1.Text) ||
string.IsNullOrEmpty(rBox_2.Text) ||
string.IsNullOrEmpty(rBox_3.Text))
return;
var box1 = GetNumber(rBox_1.Text);
var box2 = GetNumber(rBox_2.Text);
var box3 = GetNumber(rBox_3.Text);
rBox_4.Text = ((box1 + box2 + box3)/3).ToString();
}
You have 2 options for adding the Calculate function:
add it in each rBox_1_PreviewTextInput function as follows:
if(e.Handled)
{
Calculate();
}
or create a button (named button1)
private void button1_Click(object sender, EventArgs e)
{
Calculate();
}
Some Comments: why the string.IsNUllOrEmpty in Calculate?
-> Your GetNumber function does not catch any false string values like Empty. Or you work with tryparse in the GetNumber function or you catch the empty values before you go into the function.
Try using TryParse Method :
int number = Int32.Parse(arg); /*Instead of this line in your code use below.*/
A possible duplicate thread
I would Suggest that you should Add validation to your 1st 3 Test-boxes using PreviewTextInput in that way, you do not have to try parse int in your c# code and will reduce the chance of errors in your code
Related
I have been given an assignment on C# window form where I get to calculate an input textbox from a user, the user wants to input a value and then presses a radiobutton(square root) then clicks a normal button to get the result. Is it possible to get the result in a textbox (instead of a label)? If so, how do I do that using 'methods' (linking methods to the button_click one)? Also, why do I need to return a parameter value of a method? it doesn't let me execute without returning ;/
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int square(int A)
{
if (rbSquare.Checked)
{
Math.Sqrt(A);
return Convert.ToInt32(Math.Sqrt(A));
}
else
{
return A;
}
}
private void btncalculate_Click(object sender, EventArgs e)
{
int firstNum = Convert.ToInt32(tbinput.Text);
int squareRoot = square(firstNum);
tbResult.Text = "" + squareRoot;
}
}
}
Is it possible to get the result in a textbox (instead of a label)?
Sure. Set the text property of the text box, just like you would set the label text of a label.
why do I need to return a value from a method?
You said that square returns an int always, but you only return an int if the checkbox is checked. The compiler is reminding you that you need to return an int always in order to fulfill the contract that you promised. What value should you return if the checkbox is not checked?
I'm trying to create a Calculator with a Class. However using references from the internet particularly from this website (https://www.sourcecodester.com/tutorials/c/7548/simple-calculator-using-class-c.html)
It did not mention to declare "Information" or whatsoever.
When I typed in the code, the error list return with Information does not exist in current context.
Is there a way to modify the code below? Thank you so much.
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();
}
private void Form4_Load(object sender, EventArgs e)
{
}
public void RadioButton_Click(object sender, System.EventArgs e)
{
//call a constructor method and return to cal as an instance of a class
calculate cal = new calculate();
//declaring the string variable represent as a textbox
string txtnum1 = TextBox1.Text;
string txtnum2 = TextBox2.Text;
//declaring the double variable
double dbl_val1 = default(double);
double dbl_val2 = default(double);
if (**Information**.IsNumeric(txtnum1) && **Information**.IsNumeric(txtnum2)) //check if the textbox has a numeric value
{
//convert the string to double
dbl_val1 = double.Parse(txtnum1);
dbl_val2 = double.Parse(txtnum2);
//get the value of the converted variable
//to pass it into the variable in the class
cal.num1 = dbl_val1;
cal.num2 = dbl_val2;
//the condition is, if the radiobutton is clicked,
//the operation of MDAS executes.
if (Radio_Multiplication.Checked)
{
//result:
cal.multiply(); //call a subname in a class for multiplying
}
else if (Radio_Addition.Checked)
{
//result:
cal.add(); //call a subname in a class for adding
}
else if (Radio_Subtraction.Checked)
{
//result:
cal.subtract(); //call a subname in a class for subtracting
}
}
else
{
//the result is:
//if the textbox is empty or has a string value
TextBox3.Text = "Enter a number";
return;
}
//put the result of the MDAS to a textbox.
TextBox3.Text = cal.total.ToString();
}
}
I had a quick look at the link and they don't appear to have declared Information anywhere nor have they indicated that they've overridden anything so...I don't know.
That line, however, is just validating that the information entered into the two text boxes are actually numbers and not anything else that can't be calculated.
There are lots of methods you could use to check those numbers. Options would include, but are not limited to:
if(Int32.TryParse(txtNum1, out int temp1) && Int32.TryParse(txtNum2, out int temp2))
{
do stuff;
}
or
if(txtNum1.All(char.IsDigit) && txtNum2.All(char.IsDigit))
{
do stuff;
}
There are other options, but those two might be worth looking into.
Downloading the sample project, I had a look at what Information refers to. Turns out, it's a class from the Microsoft.VisualBasic namespace, presumably for exposing certain aspects of the VB core library to all .NET languages. You can use it in your program by adding a reference to Microsoft.VisualBasic to your project and adding:
using Microsoft.VisualBasic;
to the top of your code file.
(Personally, I can't imagine that this approach is terribly efficient. It's supposed to take an object and determine if it can be evaluated as a number, and I have no idea what approaches it uses to make that deduction based on any random object. You would probably be better off using one of the alternatives that Benny O'Neill suggests.)
I have a problem with my textbox. I wanted that one can manually set the interval of the x- and y-axis for a chart in the GUI over two textboxes. That works but when I type a char in or when I typed an int in and delete it, the program crashes immediately and I get a System.FormatException (without clicking the button to accept the changes). How can I solve it that one can just type in different signs without immediately crashing the program? My code below:
public void textBox2_TextChanged(object sender, EventArgs e)
{
x_axis_num = Convert.ToInt32(xAxisBox.Text, usC);
}
private void yAxisBox_TextChanged(object sender, EventArgs e)
{
y_axis_num = Convert.ToInt32(yAxisBox.Text);
}
That gets passed to another event:
chart1.ChartAreas[0].AxisX.Interval = x_axis_num;
chart1.ChartAreas[0].AxisY.Interval = y_axis_num;
In the line x_axis_num = Convert.ToInt32(xAxisBox.Text, usC);, you are taking whatever is in the text box and try to convert it to an integer value.
What do you think the conversion of "Hey, I'm not a number!" will do? It will crash horribly, basically because that text is not, and never will be, a number.
Instead, you can use the Int.TryParse method which will take any text and TRY to convert it to a number.
If the conversion is successful, then no problem. If it was not successful, then you get a false value on a flag indicating the text could not be converted.
Example:
int number;
bool result = Int32.TryParse(YourTextBox.Text, out number);
If the conversion is successful, then number has the value, otherwise, result is false so do something like this then:
if(result)
{
xAxisBox.Text = number.ToString();
x_axis_num = number;
}
else
{
xAxisBox.Text = string.Empty;
// Be careful here with what you set.
// This is the value you will set when the Text box has a non numeric value!
x_axis_num = 0;
}
I've found different help through this website but still can't seem to convert a string to int. I've tried many different ways. Here are two of them. On button_click I need to read the textboxes and convert them to int so I can perform standard logic on them. (a > b functions). Below the first section is what I'm using to force the use of numbers during entry into the text boxes.
private void write_button_Click(object sender, EventArgs e)
{
int mat_od1 = int.Parse(matod_box.Text); //Input string in wrong format.
int mat_id1 = int.Parse(matid_box.Text);
int fod1 = int.Parse(fod_box.Text);
int fid1 = int.Parse(fid_box.Text);
int hp1 = int.Parse(hp_box.Text);
//This next section is just to show something else I've tried.
decimal mat_od = Convert.ToDecimal(matod_box.Text); //Same error.
decimal mat_id = Convert.ToDecimal(matid_box.Text);
decimal fod = Convert.ToDecimal(fod_box.Text);
decimal fid = Convert.ToDecimal(fid_box.Text);
decimal hp = Convert.ToDecimal(hp_box.Text);
decimal pass_od = mat_od;
}
private void fod_box_TextChanged(object sender, EventArgs e)
{
try
{
int numinput = int.Parse(fod_box.Text);
if (numinput < 1 || numinput > 500)
{
MessageBox.Show("You must enter a number between 0 and 500.");
}
}
catch (FormatException)
{
MessageBox.Show("You need to enter a number.");
fod_box.Clear();
}
Any help would be appreciated.
instead of int.Parse() you should use int.TryParse(string,out int)
this way you would be able to chek the output and decide wether the string was correctly parsed or not
int i;string s="";
if(int.TryParse(s,out i))
{
//use i
}
else
{
//show error
}
The int.parse conversion should work, as in this sample:
string s = "111";
int i;
if (int.TryParse(s, out i))
{
Console.Write(i);
}
else
{
Console.Write("conversion failed");
}
Are you sure you actually provide legal input for your ints? In any case, you should use TryParse like I did in my sample. Theres no need to use try..catch where you can use boolean methods provided by the framework, which will get you the same result..
All depends on what you are allowing to be put in the text box.
If it might not be a string that can be converted to an integer, including blank, then something like
int value;
if (int.TryParse(SomeString, out value)
{
// it is an int
}
else
{
// it's not an int, so do nothing raise a message or some such.
}
In addition to using Int32.TryParse in the button Click event handler as others have pointed out, you need to be careful what you're doing in the TextBox Changed event handler. You're code here is flawed:
private void fod_box_TextChanged(object sender, EventArgs e)
{
try
{
int numinput = int.Parse(fod_box.Text);
...
}
catch (FormatException)
{
MessageBox.Show("You need to enter a number.");
fod_box.Clear();
}
Calling foo_box.Clear() will clear any text from the textbox, calling the TextChanged handler to be executed again (unless the TextBox was already empty). So if you enter a non-numeric value, your message box will be displayed twice - the first time when it attempts to parse your non-numeric value, the second time when it attempts to parse an empty string as a result of the call to Clear().
In general, I'd avoid doing validation in the Changed event handler.
I am writing a c# windowsform application for addition of two entries in a single text box.
I have 1 text box, 1 add button and 1 result button.
I need to achieve following algo,
User enter the no in text box. It will be stored in int n1.
User will press add button. At this time the content of the textbox.text will be get cleared and user must be able to enter the secound value in it.
This secound value will get stored in int n2.
Now when user click on result button he should get int result=n1+n2
I have written following in add buttons's click event,
n1=convert.Int32(textbox1.text);
textbox1.text="";
n2=convert.Int32(textbox1.text);//exception occures here
And result button's click event has,
textbox1.text=result.tostring();
I leanred the working of this program and find out that it is due to NULL value assignment to int n2.
I am bit confused how can I achieve above problem using single textbox?
Is there any way to provide the textbox.txt value through user through textbox field only?
Is there any property of textbox which I need to set?
I am very new to .net! Please help!
Thanks in advance for your kind attention!
move n2 = Convert.Int32(textbox1.Text); to your result button's click event
Add button click event:
n1=convert.Int32(textbox1.text);
textbox1.text="";
result button's click event:
n2=convert.Int32(textbox1.text);
result=n1+n2;
textbox1.text=result.tostring();
try something like this:
private int result=0;
addMethod()
{
//here you can use also int.TryParse
if(string.isnullorempty(textbox1.text.trim()))
textbox1.text="0";
result+=convert.toint32(textbox1.text);
textbox1.text=string.empty;
}
resultMethod()
{
textbox1.text=result.tostring();
}
look at the folloing code
private int i = 0;
private int[] a = new int[2];
private void button1_Click(object sender, EventArgs e)
{
int b;
if(Int32.TryParse(textBox1.Text, out b))
{
a[i] = b;
i++;
textBox1.Text = "";
}
else
{
MessageBox.Show(#"Incorrect number");
}
}
private void resultbutton2_Click(object sender, EventArgs e)
{
int sum = a[0] + a[1];
MessageBox.Show("Sum: " + sum);
}
}
You code contains a couple of errors:
You are using Int32 Convert.ToInt32(String) which is bad, because will throw an exception if the user enters something that can't be cast to an Int32, you should use Boolean Int32.TryParse(String, out Int32) instead, and check if the conversion is successful.
You are calling n2 = Convert.ToInt32(textbox1.Text); right after you set textbox1.Text = ""; and this is also bad, because it won't wait for a user input, it will try to convert an empty string to an integer right away, which will yield an exception.
You can't know when the user has finished inserting his number, so you have to rely to something external to the TextBox to let you know you should perform the addition.
Try the following:
Place a TextBox.
Place a Button.
Initialize a "grandTotal" integer variable to zero.
When the user press the button, parse the content of the TextBox in a temporary "submittedValue" integer variable, then sum this temporary variable to your "grandTotal" variable, and display the resulting "grandTotal" variable value.
This way you'll be able to continuously perform the addition operation on the previous total.
Example
The global variable:
protected Int32 GrandTotal = 0;
The Button click event handler:
Int32 currentValue = 0;
if (Int32.TryParse(userValue.Text, out currentValue))
{
GrandTotal += currentValue;
MessageBox.Show(String.Format("The new total is: {0}", GrandTotal));
}
else
{
MessageBox.Show("Invalid value!");
}
I have no idea why you are doing it in this fashion.
Still you can do this as
Declare n1, n2 as int? at the form level
Then in your Add click event do it in this fashion
if (! n1.HasValue)
{
n1 = int.Parse(textBox1.Text);
}
n2 = int.Parse(textBox1.Text);
textBox1.Text = "";
if you are going to do this for lotz of number then use List<int?> myIntList = new List<int?>() and your add event would be
myIntList.Add(int.Parse(textBox1.Text));
textBox1.Text = "";
and the result is int? result = myIntList.Sum();