1
votes

I am familiar with validation controls in .Net when validating textboxes on my form but not how to do it with C#. I did some research, and I know the basics of validation, like making sure that a control is not null.

But how do you test for characters? I have a textbox ID field that can only be numeric. Nothing I have found from research has used anything like that; it is mostly IsNullOrEmpty.

How do you implement something like that to test for a numeric value in a string field?

if (string.IsNullOrEmpty(rTxtBoxFormatID.Text))
{
    ValidationMessages.Add("Missing Product Number");
}

I solved this below, I needed to compare it to comobox.selectedindex in the if statement.

if (string.IsNullOrEmpty(cmboBoxStock.SelectedIndex.ToString()))
{
     rLblStockIDError.Text = "Missing Stock Number";
}
3
How do you check in C# if a String represents a number? - SJuan76

3 Answers

2
votes

You can use Int32.TryParse or Double.TryParse to check if the string is a number.

Using Int32.TryParse

int number;
string value = "123";
bool result = Int32.TryParse(value, out number);

Using Double.TryParse

double number;
string value = "123.123";
bool result = Double.TryParse(value, out number)

Your code would be

int number;
if (!Int32.TryParse(rTxtBoxFormatID.Text, out number))
{
    ValidationMessages.Add("Missing Product Number");
0
votes

You can use regular expression to check for any non numeric characters in the string.

Regex r = new Regex(@"\D");
if (!r.IsMatch(rTxtBoxFormatID.Text))
{
    // The text contains only numeric characters
}

\D Matches any character other than a decimal digit. More about Regular Expression.

0
votes

instead of do it at c# code, u can use RegularExpressionValidator,RequiredFieldValidator,regex at the aspx

<asp:TextBox ID="txtNo" runat="server"/>
<asp:Button ID="btnSubmit" runat="server" Text="Submit"/>
<asp:RegularExpressionValidator ID="regexpName" runat="server" ErrorMessage="Product Number can only be numeric" ControlToValidate="txtNo" ValidationExpression="^[0-9]$" />
<asp:RequiredFieldValidator runat="server" id="reqName" controltovalidate="txtNo" errormessage="Missing Product Number" />

http://www.w3schools.com/aspnet/aspnet_refvalidationcontrols.asp

http://msdn.microsoft.com/en-us/library/ff650303.aspx

http://www.dotnetperls.com/regex-match