user2334930
user2334930

Reputation: 11

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

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.

Upvotes: 1

Views: 2046

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502806

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.

Upvotes: 1

Related Questions