Reputation:
Essentially, I'm trying to check if textbox2.Text
contains anything that isn't an integer. This is an incredibly inefficient way of doing it, but it's the only way I could figure out. Is there anything better that I could do?
char[] ca = textBox2.Text.ToCharArray();
foreach (char c in ca)
{
string s = "1234567890";
char[] ca2 = s.ToCharArray();
if (c != ca2[0] && c != ca2[1] && c != ca2[2] && c != ca2[3] && c != ca2[4] &&
c != ca2[5] && c != ca2[6] && c != ca2[7] && c != ca2[8] && c != ca2[9])
{
MessageBox.Show("Non-integer detected in text box.");
EndInvoke(null);
}
}
int i = int.Parse(textBox2.Text);
Upvotes: 0
Views: 2601
Reputation: 136104
Starting with your code, there is a bunch of things wrong
0123456789
for every character, you could have done that once outside the loopchar.IsDigit
char[] ca = textBox2.Text.ToCharArray();
foreach (char c in ca)
{
if(!char.IsDigit(c))
{
MessageBox.Show("Non-integer detected in text box.");
EndInvoke(null);
}
}
But you dont even need to do the loop yourself, you can use a Linq method to check Any
elements satisfy for a boolean condition
var hasAnyNumbers = textBox2.Text.ToCharArray().Any(char.IsDigit);
But at that point you're trying to parse it to an integer, so I suspect what you meant to ask is "How do I check all the characters are integers" - which is kind of the opposite
var isAllNumbers = textBox2.Text.ToCharArray().All(char.IsDigit);
But, as the other answer states - theres a method for that - int.TryParse
.
Upvotes: 2
Reputation: 37299
Use IsLetter
:
bool containNonLetter = textBox2.Text.Any(c => !char.IsLetter(c));
But as your goal is to parse it to an int
use instead TryParse
:
int result;
if(int.TryParse(textBox2.Text,out result))
{
//Use result
}
Upvotes: 1