textbox formatting - c#

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

Related

Restrict Dot( . ) in Datagridview Cell at start of the Cell

I am developing an Point of Sale application in C# dot Net which contains a datagridview.
I want to restrict some cells value of datagridview to following thing.
Do not enter a Dot(".") at the beginning of the cell (This is really needed).
Do not enter any alphabet or any other character. (I have developed this but needed an improved idea)
Only Enter Numerical values with negative numbers too. (I have developed this but needed an improved idea)
Guide my in this case.
Following is my Code
private void Numeric_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.' && e.KeyChar != 46)
//if (!char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1) && ((sender as TextBox).Text.IndexOf('.') != 1))
{
e.Handled = true;
}
}
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyPress -= new KeyPressEventHandler(Numeric_KeyPress);
if (dataGridView1.CurrentCell.ColumnIndex == 1)
{
TextBox tb = e.Control as TextBox;
if (tb != null)
{
tb.KeyPress += new KeyPressEventHandler(Numeric_KeyPress);
}
}
}
The easiest way is to handle the CurrentCellDirtyStateChanged event.
I'm using a regular expression to validate the value. This code allows you to enter only numbers including negative.
private void DataGridView_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
var cell = dataGridView.CurrentCell;
if (cell.ColumnIndex != 1)
return;
string value = cell.EditedFormattedValue.ToString();
string pattern = #"^-$ | ^-?0$ | ^-?0\.\d*$ | ^-?[1-9]\d*\.?\d*$";
if (Regex.IsMatch(value, pattern, RegexOptions.IgnorePatternWhitespace))
{
dataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
else
{
dataGridView.CancelEdit();
}
}
Note: this code will not allow users to enter numbers in their own culture.

What number you deleted with backspace

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;
}
}

Making first letter of a textbox upper case

I'm having trouble with this code. I want it to make the first letter of the Textbox upper case, but if the textbox is empty the program crashes. I know the problem is to do with the length of the substring, so if anyone can help me fix this it would be great!
NB: The name of the textbox is richTextBoxGuess and this code runs every time the text in the textbox changes.
if (char.IsLower(Convert.ToChar(richTextBoxGuess.Text.Substring(0, 1))) ) // Checks if first letter is lower case
{
richTextBoxGuess.Text = richTextBoxGuess.Text.Replace(richTextBoxGuess.Text.Substring(0, 1), richTextBoxGuess.Text.ToUpper()); // Changes first letter to uppercase
richTextBoxGuess.SelectionStart = 2; // Puts cursor after first letter
}
This will not destroy the previous formatting of the content:
private void richTextBoxGuess _TextChanged(object sender, EventArgs e)
{
if (richTextBoxGuess .Text.Length <= 0) return;
string s = richTextBoxGuess.Text.Substring(0, 1);
if (s != s.ToUpper())
{
int curSelStart = richTextBoxGuess.SelectionStart;
int curSelLength = richTextBoxGuess.SelectionLength;
richTextBoxGuess.SelectionStart = 0;
richTextBoxGuess.SelectionLength = 1;
richTextBoxGuess.SelectedText = s.ToUpper();
richTextBoxGuess.SelectionStart = curSelStart;
richTextBoxGuess.SelectionLength = curSelLength;
}
}
Note that it doesn't not keep track of the changes and will not restore them when you keep adding at the front..
If you need culture invariance use the CultureInfo.CurrentCulture parameter of ToUpper()!
Check if the richTextBoxGuess is null or empty
if( richTextBoxGuess != ""){ // or different from null
if (char.IsLower(Convert.ToChar(richTextBoxGuess.Text.Substring(0, 1))) ){
//your code
}
}
Write this extension method:
public static string CapitalizeFirstLetter(this string input)
{
if (string.IsNullOrEmpty(input))
{
return input;
}
return input.Substring(0, 1).ToUpper(CultureInfo.CurrentCulture) + input.Substring(1);
}
And then use it as
richTextBoxGuess.Text = richTextBoxGuess.Text.CapitalizeFirstLetter();
private void _capitalizeFirstWord(Object sender, KeyPressEventArgs e)
{
if (_richTB.Text.Trim() == String.Empty)
{
e.KeyChar = char.ToUpper(e.KeyChar);
}
}
If you want to capitalize every word
char _pre,_cur;
_pre=' ';
private void _capitalizeEveryWord(Object sender, KeyPressEventArgs e)
{
_cur = e.KeyChar;
if (_richTB.Text.Trim() == String.Empty)
{
e.KeyChar = char.ToUpper(e.KeyChar);
}
e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == ' ' && (!(_cur == _pre)) || e.KeyChar == '.' && (!(_pre == _cur)));
_pre=_cur
}

TextBox with maxvalue

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 = "";
}
}
}
}

Limit Numbers after Decimal on Key Press Event

I am using the following code to take only digits from user and only one decimal point , that is working fine for me on KeyPress Event :
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
Now I want to Limit the numbers/Digits after the decimal/dot i.e 35.25468, means it take only 6 numbers/digits after the dot/decimal.
Update me !
private void price_tb_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
if (!char.IsControl(e.KeyChar))
{
TextBox textBox = (TextBox)sender;
if (textBox.Text.IndexOf('.') > -1 &&
textBox.Text.Substring(textBox.Text.IndexOf('.')).Length >= 3)
{
e.Handled = true;
}
}
}
This code will help you. It takes only one decimal place and two digit after one decimal place and you can change it accordingly.
you can add an additional check like this
TextBox textBox = (TextBox) sender;
if (textBox.Text.IndexOf('.') > -1 &&
textBox.Text.Substring(textBox.Text.IndexOf('.')).Length >=3)
{
e.Handled = true;
}
Note, the Substring will include the '.' and hence the check is >=3.
On the keypress event, and or validate event, count the number of chars after decimal point. On key press, suppress it. on validate, remove extra decimal places. Make sure you're getting the decimal point char from NumberFormatInfo, not all cultures use '.', ie. in France, their decimal point is actually a comma
On keypress, format the string and set the textBox.Text to the formatted string.
TextBox.Text = String.Format("{0:N3"}", textBox.Text)
This particular format cuts off the number at the 3rd decimal.
I had textBox.SelectionLength == 0 to allow the modification of selected text:
private void price_tb_KeyPress(object sender, KeyPressEventArgs e) {
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.') {
e.Handled = true;
}
TextBox textBox = (TextBox)sender;
// only allow one decimal point
if (e.KeyChar == '.' && textBox.Text.IndexOf('.') > -1) {
e.Handled = true;
}
if (!char.IsControl(e.KeyChar) && textBox.SelectionLength == 0) {
if (textBox.Text.IndexOf('.') > -1 && textBox.Text.Substring(textBox.Text.IndexOf('.')).Length >= 3) {
e.Handled = true;
}
}
}
The issue I have with the answer of Both FM is that you cannot edit the text when you have entered a decimal place and two decimals.
This code also takes a minus amount.
private void TextBoxAmount_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar))
{
// OK, but not more than 2 after the [.]
if (((TextBox)sender).Text.Contains('.'))
{
if (((TextBox)sender).Text.IndexOf('.') + 2 < ((TextBox)sender).Text.Length)
{
if (((TextBox)sender).SelectionStart > ((TextBox)sender).Text.IndexOf('.'))
{
e.Handled = true;
}
}
}
}
else if (char.IsControl(e.KeyChar))
{
// Always OK
}
else if (e.KeyChar == '.' && !((TextBox)sender).Text.Contains('.'))
{
// First [.] == OK
}
else if (e.KeyChar == '-' && !((TextBox)sender).Text.Contains('-'))
{
// First [-] == OK
}
else
{
e.Handled = true;
}
}
private void TextBoxAmount_KeyUp(object sender, KeyEventArgs e)
{
if (((TextBox)sender).Text.Contains('-'))
{
((TextBox)sender).Text = $"-{((TextBox)sender).Text.Replace("-", string.empty)}";
}
}

Categories

Resources