Error provider checked number of digits of input textbox - c#

I used from Error Provider in C# winform. in my form have textbox. error provider checked it that it contain two number. it means that input is digit and number of digit is two number. when input is 2 char , error provider is worked but when input is char and digit, error provider didn't worked.
please check my code.
private void textbox1_Leave(object sender, EventArgs e)
{
string text = textbox1.Text;
bool hasDigit = false;
foreach (char letter in text)
{
if (char.IsDigit(letter))
{
hasDigit = true;
break;
}
}
// Call SetError or Clear on the ErrorProvider.
if (!hasDigit )
{
errorProvider1.SetError(textbox1, "Please enter digit");
}
else if(hasDigit)
{
if (text.TextLength != 2)
{
errorProvider1.SetError(textbox1, "Number of digit is two number");
}
else
errorProvider1.Clear();
}
}

So you want to ensure that all chars are digits. But you're checking only the first, if that's a digit you're breaking the loop:
foreach (char letter in text)
{
if (char.IsDigit(letter))
{
hasDigit = true;
break;
}
}
Instead you could use Linq for this. Enumerable.All is made for this purpose:
bool allDigits = text.All(c => Char.IsDigit(c));
(but maybe i'm totally off the track since the question is not so clear imho)

Related

WPF - Need to change characters of a text box only with a specific string

I'm attempting to create a tool for supporting users on my network, basically I have a textbox that you would enter a hostname to. I'm wondering if there is a way to append a character to the text box only when a 6 digit number is entered in the box. If it's anything else, leave it alone.
Basically if the number is 123456 then put a "C" at the beginning "C123456"
but if someone already put the C in - don't do anything.
Also there would be other characters (for other hostnames) that I would not want changed. Only if 6 digits are entered, to put a "c" in front.
Sample code:
This is what i have so far:
private void IPfind(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
TextBox tb = (TextBox)sender;
string text = tb.Text.ToUpper();
int num;
if (int.TryParse(text, out num))
{
// it is an integer. Simply add a C at the begining if it has enough characters
if (text.Length == 6)
{
tb.Text = 'C' + text;
tb.CaretIndex = tb.Text.Length;
}
else
{
}
Ipbox.Clear();
try
{
// Host Name resolution to IP
IPHostEntry host = Dns.GetHostEntry(Assetbox.Text.Trim());
IPAddress[] ipaddr = host.AddressList;
// Loop through the IP Address array and add the IP address
foreach (IPAddress addr in ipaddr)
{
// Finds the IP V4 address
if (addr.AddressFamily == AddressFamily.InterNetwork)
Ipbox.Text = (addr.ToString());
}
}
Use if blocks to check everything. I explain different parts in comments:
bool _changing = false; // since you are going to change Text you need this to stop a loop or other errors
private void Tb_TextChanged(object sender, TextChangedEventArgs e)
{
if (_changing)
return;
_changing = true;
TextBox tb = (TextBox)sender;
string text = tb.Text.ToUpper();
if (text == null || text.Length == 0)
{
// The user has not enter enough characters yet
return;
}
int num;
if (int.TryParse(text, out num))
{
// it is an integer. Simply add a C at the begining if it has enough characters
if (text.Length == 6)
{
tb.Text = 'C' + text;
tb.CaretIndex = tb.Text.Length;
}
else
{
// let use to continue typing
}
}
else
{
// it is not an integer
//check if it starts with P or C
if (text[0] == 'C' || text[0] == 'P')
{
string textrest = text.Remove(0, 1);
if (textrest.Length == 0)
{
// it is just a C or P
return;
}
if (int.TryParse(textrest, out num))
{
// it became an integer after removing the first char. It is OK then.
}
else
{
// it is not a number and removing the first C or P did not solve the problem
// throw new FormatException();
// or
MessageBox.Show("Wrong Format. Enter ###### or C###### or P#######");
}
}
else
{
// it is not a number and the reason is not because it starts with C or P
// throw new FormatException();
// or
MessageBox.Show("Wrong Format. Enter ###### or C###### or P#######");
}
}
_changing = false;
}
So I think Regex could be really useful here,
make your textbox then make a textchanged event like so in the XAMl,
<TextBox x:Name="textBox" TextChanged="textBox_TextChanged"/>
Then in C#(code behind), you can add the code to the event,
private void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
var pattern = new Regex(#"(\w[0-9]{6})"); //This is a regex pattern, you can make it much more intelligent, like if you just want P or C chars to accepted rather than any letter
var isThereMatch = pattern.Match(textBox.Text); // Is there a match?
string strThingIwannaSAVE = isThereMatch.ToString(); //If there is save that string so you can manipulate it
if (textBox.Text.Length > 6) //only execute the following code if you have enough characted in your box
{
if (string.IsNullOrWhiteSpace(strThingIwannaSAVE)) //if there is no match or its just whitespaces for some reason, empty out your box or display a message or whatever else
{
MessageBox.Show("Wrong input");
textBox.Text = String.Empty;
}
else
{
//String is good, add it to a database? do something to it?
}
}
}
EDIT
If you want to just match P or C characters plus the numbers, make two regex patterns,
var pattern = new Regex(#"(c{1}[0-9]{6})");
var pattern2 = new Regex(#"(p{1}[0-9]{6})");
Then check textbox for matches
Thanks huge to both #JohnChris and #Ramin
I used both solutions to fix this
TextBox tb = (TextBox)sender;
string text = tb.Text;
if (Regex.IsMatch(text, #"^\d+$") && text.Length == 6)
{
tb.Text = 'C' + text;
tb.CaretIndex = tb.Text.Length;
}

Checkbox self checking C#

Here is my problem and yes I am a newbie
I have a form (dialog) that has two checkboxes (chbxAlpha and chbxBravo), two textboxes (tbxAlpha and tbxBravo) which can only receive 6 char , and two buttons (Submit and Cancel)
The form is loaded by an error event
When the form is loaded if Alpha is the error then I will check Alpha Checkbox and then fill in the error in Alpha Textbox
If chars are < > than 6 a messagebox appears alerting the user that they must submit 6 chars no more and no less
When I press the submit button the form then automatically checks Bravo Checkbox and I have to fill it out even there has been no error
I cannot figure out why
Below is the code
private void btnSubmit_Click(object sender, EventArgs e)
{
if (chbxAlpha.Checked = true && tbxAlpha.Text.Length != 6)
{
MessageBox.Show("A valid entry requires 6 digits. Please use forward zeros if data is less than 6 digits eg 1234 = 001234.Thankyou");
tbxAlpha.Text = "";
tbxAlpha.Focus();
}
else
{
this.DialogResult = DialogResult.OK;
}
if (chbxBravo.Checked = true && tbxBravo.Text.Length != 6)
{
MessageBox.Show("A valid entry requires 6 digits. Please use forward zeros if data is less than 6 digits eg 1234 = 001234.Thankyou");
tbxBravo.Text = "";
tbxBravo.Focus();
}
else
{
this.DialogResult = DialogResult.OK;
}
}
private void chbxBravo_CheckedChanged(object sender, EventArgs e)
{
if (chbxBravo.Checked == true)
{
tbxBravo.Visible = true;
tbxBravo.Focus();
}
}
private void chbxAlpha_CheckedChanged(object sender, EventArgs e)
{
if (chbxAlpha.Checked == true)
{
tbxAlpha.Visible = true;
tbxAlpha.Focus();
}
}
}
}
The other question I have is how can I prevent Null char from being used eg. 123space56
Appreciate any help
JJ
It looks like you are using an assignment operator rather than an equality operator in both your if statements in btnSubmit_click function.
In answer to your second question, you can use a Regex to check that all 6 characters are digits.
private void btnSubmit_Click(object sender, EventArgs e)
{
Regex regexIs6Digits = new Regex(#"^\d{6}$");
if (chbxAlpha.Checked && !regexIs6Digits.IsMatch(tbxAlpha.Text))
{
MessageBox.Show("A valid entry requires 6 digits. Please use forward zeros if data is less than 6 digits eg 1234 = 001234.Thankyou");
tbxAlpha.Text = "";
tbxAlpha.Focus();
}
else
{
this.DialogResult = DialogResult.OK;
}
if (chbxBravo.Checked && !regexIs6Digits.IsMatch(tbxBravo.Text))
{
MessageBox.Show("A valid entry requires 6 digits. Please use forward zeros if data is less than 6 digits eg 1234 = 001234.Thankyou");
tbxBravo.Text = "";
tbxBravo.Focus();
}
else
{
this.DialogResult = DialogResult.OK;
}
}

Checking whether a text box contain only digits

I am done with this problem(using an alternative method). But still don't know why the following method is not working. Please help
Aim: when leave from a text box
check whether it contain only digits-then allow to leave.
If not show an error provider.
check whether string length is not more than 7 and not 0 -then allow to leave.
if not show an error provider.
Code that doesn't seem working is given below! :
private void textBox24_Validating(object sender, CancelEventArgs e)
{
bool result = true;
foreach (char y in textBox24.Text)
{
while (y < '0' || y > '9')
result = false;
}
if (result == false)
{
errorProvider4.SetError(textBox24, "Enter digits only");
textBox24.Focus();
}
else if (textBox24.Text.Length == 0)
{
errorProvider4.SetError(textBox24, "Enter the value");
textBox24.Focus();
}
else if (textBox24.Text.Length > 7)
{
errorProvider4.SetError(textBox24, "Maximum length is 7 digits");
textBox24.Focus();
}
else
errorProvider4.Clear();
}
problem with this code:
when I enter input other than digits, it gets stuck.
May be this wont be a big question. However help me.
code that now I am using:
private void textBox24_Validating(object sender, CancelEventArgs e)
{
int check = 123;
bool result = int.TryParse(textBox24.Text, out check);
if (result == false)
{
errorProvider4.SetError(textBox24, "Only digits are allowed");
textBox24.Focus();
}
else if (textBox24.Text.Length > 7)
{
errorProvider4.SetError(textBox6, "Invalid value");
textBox24.Focus();
}
else
errorProvider4.Clear();
}
inside while loop you have condition if true you set the result as true but loop running forever because condition again true.
foreach (char y in textBox24.Text)
{
while (condition) // this is run forever if true
result = false;
}
you can use break; if true case like below
foreach (char y in textBox24.Text)
{
while (condition){
result = false;
break;
}
}
Few more Suggestion..
TextBox control having property called MaxLength you can set it as 7 to limit user input up to 7 characters
if you need to allow only digits don't use int.TryParse method. if input with decimal points will pass the validation.
to check string contains only digits you can use code like if (textBox1.Text.ToCharArray().Any(c=>!Char.IsDigit(c)))
if validation fail you need to set e.Cancel = true;

Limiting the length and input mask in a TextBox

I need to limit the number of digits allowed in my TextBox in C#.
I also need to create the validation so that it will resemble a mobile number, meaning it must begin with 07 and have a total of 11 digits.
Any suggestions?
You can use a MaskedTextBox to provide a controlled input value. A "07" followed by 11 digit mask would be \0\700000000000.
You don't have any code as example, so, I would type mine.
To limit the number of characters you should type this code:
private bool Validation()
{
if (textBox.Text.Length != 11)
{
MessageBox.Show("Text in textBox must have 11 characters", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
textBox.Focus();
return false;
}
return true;
}
If you want that text in your textBox begin with "07", you should type this code:
private bool Validation()
{
string s = textBox.Text;
string s1 = s.Substring(0, 1); // First number in brackets is from wich position you want to cut string, the second number is how many characters you want to cut
string s2 = s.Substring(1, 1);
if (s1 != "0" || s2 != "7")
{
MessageBox.Show("Number must begin with 07", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
textBox.Focus();
return false;
}
return true;
}
You can merge this in one method ofcource, and you can call it where ever you want. If you want to call in some method(for example when you click on accept button) just type this code:
private void buttonAccept_Click(object sender, EventArgs e)
{
if (Validation() == false) return;
}

C# Textbox validation should only accept integer values, but allows letters as well

if (textBox1.Text != "") // this forces user to enter something
{
// next line is supposed to allow only 0-9 to be entered but should block all...
// ...characters and should block a backspace and a decimal point from being entered....
// ...but it is also allowing characters to be typed in textBox1
if(!IsNumberInRange(KeyCode,48,57) && KeyCode!=8 && KeyCode!=46) // 46 is a "."
{
e.Handled=true;
}
else
{
e.Handled=false;
}
if (KeyCode == 13) // enter key
{
TBI1 = System.Convert.ToInt32(var1); // converts to an int
Console.WriteLine("TBI1 (var1 INT)= {0}", var1);
Console.WriteLine("TBI1= {0}", TBI1);
}
if (KeyCode == 46)
{
MessageBox.Show("Only digits...no dots please!");
e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
}
}
else
{
Console.WriteLine("Cannot be empty!");
}
// If I remove the outer if statement and skip checking for an empty string, then
// it prevents letters from being entered in the textbox. I need to do both, prevent an
// empty textbox AND prevent letters from being entered.
// thanks, Sonny5
You didn't specify where this code runs, but my assumption would be it runs on key down. Since key down is received before the character is processed and the Text property is updated, your check for .Text == "" will prevent the rest of the validation running, at least for the first character.
You should move the check for empty value on a different event than the check for the key pressed.
I think you could use the IsDigit function.
Something along these lines:
string textBoxText = "12kj3";
if (!textBoxText.Equals(String.Empty)) // this forces user to enter something
{
foreach (char c in textBoxText.ToArray())
{
if (!Char.IsDigit(c))
{
//return false;
}
}
//return true;
}
else
{
Console.WriteLine("Cannot be empty!");
}
Hope you get the idea.
You can use the following RegEx to check that it is a number "^\d+$" and required.
bool bV=false;
private void textBox1_Validated(object sender, EventArgs e)
{
TextBox textBoxText = sender as TextBox;
if (!textBoxText.Equals(String.Empty))
{
foreach (char c in textBoxText.Text.ToArray())
{
if (!Char.IsDigit(c))
{
if (!bV)
{
MessageBox.Show("Input value not valid plase Insert Integer Value");
bV = true;
textBox1.Text = String.Empty;
break;
}
}
}
}
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
bV = false;
}

Categories

Resources