int age = txtAge.Text;
I'm getting the error:
Error 2 Cannot implicitly convert type 'string' 开发者_开发问答to 'int'
int age = int.Parse(txtAge.Text);
Of course you can't, int and string are two completely different types. However, the most simple solution is:
int age = Int32.Parse(txtAge.Text);
More secure is:
int age;
Int32.TryParse(txtAge.Text, out age);
Try
int age;
bool result = Int32.TryParse(txtAge.Text, out age);
if (result)
{
// Parse succeeded and get the result in age
}
else
{
// Parse failed
}
See Int32.TryParse Method (String, Int32)
The TryParse method is like the Parse method, except the TryParse method does not throw an exception if the conversion fails. It eliminates the need to use exception handling to test for a FormatException in the event that s is invalid and cannot be successfully parsed.
精彩评论