Reputation: 113
I'm having a problem with checking textboxes and making sure there's only integers in them.
So far I'm able to confirm that there's text in the textboxes, but checking if they're integers isn't working. Here's my code that so far works.
if (textBox1.Text.Length == 0)
{
errorProvider1.SetError(textBox1, "need Cost of Disks");
return;
}
if (textBox2.Text.Length == 0)
{
errorProvider2.SetError(textBox2, "need Total disks in package");
return;
}
if (textBox3.Text.Length == 0)
{
errorProvider3.SetError(textBox3, "need the Gigabyte per disk");
return;
}
try
{
Double[] myValues = new Double[3];
myValues[0] = Double.Parse(textBox1.Text);
myValues[1] = Double.Parse(textBox2.Text);
myValues[2] = Double.Parse(textBox3.Text);
Double ppd = myValues[0] / myValues[1] / myValues[2];
ppd = Math.Round(ppd, 3, MidpointRounding.AwayFromZero);
label4.Text = ppd.ToString();
}
catch (FormatException)
{
//errorProvider1.SetError(label4, "testing1");
//errorProvider2.SetError(label4, "testing2");
//errorProvider3.SetError(label4, "testing3");
return;
}
Upvotes: 2
Views: 10802
Reputation: 1177
If you ever start using ajax tool kit, keep this for your records
<ajaxToolkit:FilteredTextBoxExtender ID="FilteredTextBoxExtender1" TargetControlID="FUND_CD" FilterType="Custom" ValidChars="1234567890" runat="server">
</ajaxToolkit:FilteredTextBoxExtender>
Upvotes: -1
Reputation: 19956
If you don't want to permit ANYTHING except numbers into the editbox, hook into keyboard events, check for characters that aren't digits and cancel them out.
When you sort out what events are needed on one textbox, just reuse same event on others, since you don't have to copy events around.
Upvotes: 0
Reputation: 34689
Using your current pattern, something like this:
int tester;
if (!Int32.TryParse(textBox1.Text, out tester))
{
errorProvider1.SetError(textBox1, "must be integer");
return;
}
Upvotes: 2
Reputation: 17568
You can use the int.TryParse method to check if the string is an integer:
int n = 0;
bool isNumber = int.TryParse(textBox1.Text, out n);
if (!isNumber)
return;
Upvotes: 0
Reputation: 2698
Override the Validating
event in your form's textboxes and then you can do a TryParse
on the contents.
public void textBox1_Validating(...)
{
// TryParse
}
Upvotes: 0