When I delete a number in a textbox with backspace I want to save that number so that I can compare it with other numbers in my other textboxes. How do I do that?
This is the code where I want to put it in:
List<TextBox> box1;
private void Form1_Load(object sender, EventArgs e)
{ box1 = this.Controls.OfType<TextBox>()
.Where(x => x.Name.StartsWith("textBox1")).ToList();
foreach (TextBox t in box1)
t.TextChanged += textBox_TC1;
}
private void textBox_TC1(object sender, EventArgs e)
{
TextBox textBox = (TextBox)sender;
if (textBox.Text.Length == 1 && allwhite == 0)
{
bool sameText = box1.Any(x => x.Text == textBox.Text &&
!x.Equals(textBox));
if (sameText)
textBox.BackColor = System.Drawing.Color.Red;
}
else if (textBox.Text.Length == 0)
{
textBox.BackColor = System.Drawing.Color.White;
}
}
I want to put my new code in 'else if (textBox.Text.Length == 0)' because I can only delete text with backspace in my textboxes and the maxlength is 1.
When I backspace something I want to compare that number to all the other textboxes in box1 and then if that number is equal to only one other textbox, it'll make that other textbox backcolor white. I have no idea how to save a number that's about to be deleted so if you could help me I'll be so happy.
You should use TextChanged event to detect changes on your TextBox, and at the end of TextChanged you should keep current value somewhere like Tag property of your TextBox and use it when you want to compare it with other values. You should not use any event other than TextChanged because the user can delete or paste values without useing keyboard.
For example you can write code like this:
...
else if (textBox.Text.Length == 0)
{
var previusText = textBox.Tag as string;
var items= box1.Where(x => x.Text == previusText && !x.Equals(textBox)).ToList();
if (items.Count()==1)
{
items[0].BackColor = System.Drawing.Color.White;
}
}
//Keep previous text
textBox.Tag = textBox.Text;
...
You could use this approach:
static void textBox1_KeyDown(object sender, KeyEventArgs e)
{
TextBox t = sender as TextBox;
switch (e.KeyCode)
{
case Keys.Delete:
case Keys.Back:
int start = e.KeyCode == Keys.Back && t.SelectionLength == 0 ? t.SelectionStart - 1 : t.SelectionStart;
int length = t.SelectionLength == 0 ? 1 : t.SelectionLength;
// you can save your char right here....!
t.Text = t.Text.Remove(start, length);
e.SuppressKeyPress = true;
break;
}
}
Related
How to prohibit the introduction of letters in textBox? That is, this construction works incorrectly
public void textBox1_KeyDown(object sender, KeyEventArgs e)
{
try
{
char s = Convert.ToChar(textBox1.Text);
if ((s <= '0') || (s >= '9'))
MessageBox.Show("You have entered a symbol! Please enter a number");
}
catch (System.FormatException)
{
MessageBox.Show("You have entered a symbol! Please enter a number");
}
}
You need to either check the key being entered in the KeyDown event (e.Key property) as the key value is added to the Text field after the event or use the TextChanged event - this would catch cut & paste operations as well.
public void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
if (!ValidNumericString(textBox1.Text))
{
MessageBox.Show("You have entered invalid characters! Please enter a number");
Dispatcher.BeginInvoke(new Action(() => textBox1.Undo()));
e.Handled = true;
}
}
public bool ValidNumericString(string IPString)
{
return IPString.All(char.IsDigit);
// OR make this check for thousands & decimals if required
}
You can use the OnKeyPress event which allows you to cancel the key event manually if you want to.
void textBox1_OnKeyPress(KeyPressEventArgs e)
{
e.Handled = true; // this won't send the key event to the textbox
}
If you want to accept only numbers and related chars (negative sign, decimal separators, ...), you can test the entered char :
void textBox1_OnKeyPress(KeyPressEventArgs e)
{
NumberFormatInfo numberFormatInfo = CultureInfo.CurrentCulture.NumberFormat;
string decimalSeparator = numberFormatInfo.NumberDecimalSeparator;
string groupSeparator = numberFormatInfo.NumberGroupSeparator;
string negativeSign = numberFormatInfo.NegativeSign;
string keyInput = e.KeyChar.ToString();
e.Handled = !(Char.IsDigit(e.KeyChar) || keyInput.Equals(negativeSign) || keyInput.Equals(decimalSeparator) || keyInput.Equals(groupSeparator));
}
This is untested code because I'm at work, but you get the idea.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (Control.ModifierKeys == Keys.Control) return; // Check if ctrl is pressed
var key = (char) e.KeyValue; // ASCII to char
if (char.IsDigit(key) || char.IsControl(key) || char.IsWhiteSpace(key)) return; // Check if "key" is a number
MessageBox.Show("You have entered a symbol! Please enter a number");
textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 1); // Remove last element
textBox1.SelectionStart = textBox1.Text.Length; // Return to initial position
}
I am working on a database application and using this class to validate numeric numbers on KeyPress event of TextBox.
The numbers may have (-) negative values with fixed decimal places (third parameter dPlaces) e.g. 10000, -1000, 12345.45, -12345.45
After adding a decimal, I am not able to edit other digits although without a decimal it is working perfectly.
Thanks in advance
public static class Util
{
public static void NumInput(object sender, KeyPressEventArgs e, int dPlaces)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.' && (e.KeyChar != '-'))
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
var a = (sender as TextBox).SelectionLength;
// only allow minus sign at the beginning
var x = (sender as TextBox).Text.IndexOf('-');
if (e.KeyChar == '-' && (sender as TextBox).Text.IndexOf('-') > 0)
{
e.Handled = true;
}
if (!char.IsControl(e.KeyChar))
{
TextBox textBox = (TextBox)sender;
if (textBox.Text.IndexOf('.') > -1 &&
textBox.Text.Substring(textBox.Text.IndexOf('.')).Length >= dPlaces + 1)
{
e.Handled = true;
}
}
}
}
Its because of Logical operation in your IF BLOCK for comparing length =3 and char = '.'.
Change that last part of your code with : (EDIT : To handle the issue of inserting text before '.')
if (!char.IsControl(e.KeyChar))
{
TextBox textBox = (TextBox)sender;
// get position of new char to be inserted
int position = textBox.SelectionStart;
if (textBox.Text.IndexOf('.') > -1 && position > textBox.Text.IndexOf('.')) // check location of new char
if(!(textBox.Text.Substring(textBox.Text.IndexOf('.')).Length <= dPlaces + 1))
{
e.Handled = true;
}
}
This will do your job..!!!
EDIT : Also Do the following to STOP Copy/Past in textbox
textbox.ShortcutsEnabled = false;
I want to make a TextBox which does not allow to enter a value above 100. Only numbers allowed, And a Numeric TextBox is not an option. This is my code for now:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)) { e.Handled = true; } // only numbers
}
Any ideas?
You should use int.TryParse to see if the parsing is successful and then compare the value to see if it is below 100.
int number;
if(int.TryParse(textBox1.Text, out number))
{
if(number <= 100)
{
//in range
}
else
{
// not in range
}
}
else
{
//invalid number
}
You can also use double.TryParse or other TryParse method depending on the type, they are safe to use, since they will return a false if the parsing fails, instead of raising an exception.
Hello, here is my solution.
private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
char c = e.KeyChar;
if ((!char.IsDigit(c) ||
Convert.ToInt32(textBox.Text + e.KeyChar) >= 101 ||
textBox.Text == "0") && c != '\b')
e.Handled = true;
}
Finally. I found a solution:
int box_int = 0; Int32.TryParse(textBox1.Text, out box_int);
if (box_int > 1050 && textBox1.Text != "") { textBox1.Text = "1050"; }
You can enter only numbers and use arrows keys and backspace. If you enter a number > than 100 or less than 1, when you press enter it will be cancelled. Copy and Past with button key down is disabled and also mouse right click to prevent the user to paste in the text box is disabled/handled. This should solve your problem in full.
First of all set:
ShortcutsEnabled property of your text box to False
this will not allow mouse right click and ctrl+V for paste in your text box.
Then add the following code:
//prevent letters, special chars, punctuation, symbols, white spaces
private void txtType1_KeyPress(object sender, KeyPressEventArgs e)
{
{
if (char.IsLetter(e.KeyChar) ||
char.IsSymbol(e.KeyChar) ||
char.IsWhiteSpace(e.KeyChar) ||
char.IsPunctuation(e.KeyChar))
e.Handled = true;
}
{
//allows only numbers between 1 and 100
string value = txtType1.Text;
if (txtType1.Text !="")
{
if (Int16.Parse(value) < 1 )
{
txtType1.Text = "";
}
else if (Int16.Parse(value) > 100)
{
txtType1.Text = "";
}
}
}
}
I m Working On A windows Form.. I Need my TextBox Not To Accept negative Values ..How Can I Do this..
IS There Any Property Availiable For Doing The same...
You need to write keypress event of textbox like :
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
You can also user numeric updown control to prevent negetive values.
UPDATE :
Ref: Sai Kalyan Akshinthala
My code will not handle the case of copy/paste. User can enter negative values by copy/paste. So I think Sai Kalyan Akshinthala's answer is correct for that case except one small change of Length >= 2.
private void textBox1_TextChanged(object sender, EventArgs e)
{
if(textBox1.Text.Length >= 2)
{
int acceptednumber = Convert.ToInt32(textBox1.Text);
if(acceptednumber < 0)
{
textBox1.Text = "";
MessageBox.Show("-ve values are not allowed");
}
else
{
textBox1.Text = textBox1.Text;
}
}
}
yes you can do write the following code part in textchanged event of textbox
if(textBox1.Text.Length >= 2)
{
int acceptednumber = Convert.ToInt32(textBox1.Text);
if(acceptednumber < 0)
{
textBox1.Text = "";
MessageBox.Show("-ve values are not allowed");
}
else
{
textBox1.Text = textBox1.Text;
}
}
just use min and pattern will not allow to enter a minus value
min="0" pattern="^[0-9]+$" in input type
I need some help with my code.
I need the following format,
12345-1234567-1
Basically I want to type just digits and when text length reaches 5, it should append '-' and again on reaching to the length of 13, again it should append '-'.
My code is doing this fine. But when I use backspace/delete, it always append '-' to the 6th and 14th location.
Here is my code,
private void nicNo_txt_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode.ToString() != "Back" || e.KeyCode.ToString() != "Space" || e.KeyCode.ToString() != "Delete")
{
if (nicNo_txt.TextLength == 5 || nicNo_txt.TextLength == 13)
nicNo_txt.AppendText("-");
}
}
Regards
Have you tried MaskedTextBox, in it you can specify a mask in whatever format you need
One below will do
For formating after changes - replace format method with anything you like:
void oTextBoxAmount_TextChanged(object sender, EventArgs e)
{
//throw new NotImplementedException();
if (sender is TextBox)
{
TextBox tb = sender as TextBox;
tb.Text = FormatAmount(tb.Text);
tb.SelectionStart = tb.Text.Length;
}
}
For filtering keys (example below filters digits but you can change conditions):
void oTextBoxAmount_KeyPress(object sender, KeyPressEventArgs e)
{
int val = (int)e.KeyChar;
if (val >= 0x30 && val <= 0x39)
{
//Digits are ok
}
else if (val == 0x08)
{
//Backspace is ok
}
else
{
//Other are disallowed
e.Handled = true;
}
}
You can use AJAX Control Toolkit's Masked Edit. It does exactly what you want.
Ajax Control Toolkit - Masked Edit