How to know the data type of value entered by user

2019-08-07 05:45发布

问题:

How to know the data type of value entered by user at runtime in textbox?

My simple example:

I've tried it by using GetType(), but it was useless, it always shows System.String, whether I enter int or String.

回答1:

If the user has typed text into a textbox, that's always a string. It's never an int. You can parse the text as an integer, but the input itself is still text.

You could speculatively try to parse it in different ways:

int intValue;
if (int.TryParse(text, out intValue)
{
    ... use intValue, then return?
}

decimal decimalValue;
if (decimal.TryParse(text, out decimalValue)
{
    ... use decimalValue, then return?
}

But fundamentally you need to understand that the user input is always a string, and how you use that string is up to you.