I am new at this forum and also in c#, I am developing a windows based form and insert a textbox to take totalmarks input and button to display result according to the given input.
I am facing problem, when I am assigning textbox value to my local variable, my code is
int totalmarks = textbox1.text ;
Kindly resolve this issue.
Also I have a question
1- How can I change datatype of textbox to my required datatype like is there any property in which we define its datatype?
Loading
VulpesPosted Jun 23, 2012, 6:59 AM
If the string is numeric, you therefore have to convert it to a number of the appropriate type (usually int, double or decimal) before you can do any calculations with it. You also need to ensure that the string does represent a valid number, otherwise you'll get an exception.
So, what I'd suggest is this:
int totalMarks;
bool isValid = int.TryParse(textBox1.Text, out totalMarks);
if (!isValid)
{
MessageBox.Show("You haven't entered a valid number. Please try again");
textBox1.Focus();
return;
}
// do something with total marks
The int.TryParse method checks to see whether textBox1.Text contains a valid integer. If it does then it converts it to an integer, assigns it to totalmarks and returns true.
If it doesn't, then it assigns 0 to totalmarks and returns false.
This is a more sophisticated version of the int.Parse method suggested by Cenk which normally does the conversion OK but throws an exception if the string can't be converted to an integer. The most common reason for such an exception is if the textbox is empty.
Cenk IsikPosted Jun 23, 2012, 6:51 AM