I have a textbox in grid view created dynamically. We can access the user input as text, but how do I check whether the text is of integer type or string type?
if (tx.Text == "")
{
tx.Text = Convert.ToString(0);
}
if (Convert.ToInt32(tx.Text) > max)
{
MessageBox.Show("Some Message", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
tx.Text = Convert.ToString(max);
}
tx is the textbox from which we are accessing the user input through tx.Text.
How can I check the type of the input parameter whether it is Integer or not?
You’re looking for the
TryParsemethod. That will tell you if a given string value can be converted into a number. And it does it all without throwing any exceptions.Sample code:
But if you’re looking to restrict the input range of the textbox (i.e., prevent the user from entering anything but numbers), this is not the correct way to go about it.
Instead, you should use a different control, such as a
NumericUpDowncontrol, or aMaskedTextBoxcontrol. These allow you to prevent the user from entering invalid input in the first place, which is much more user friendly than showing an error after the fact.In response to your comment:
C# has the
typeofkeyword, but that’s not going to help you here. The problem is, the object you’re checking is an instance of typeString. TheTextproperty of theTextBoxclass always returns an object of typeString. This is not VB 6: there are noVariantshere. What you’re checking is whether thatStringvalue can be converted into an equivalent integral representation.