In my code I use this piece of code to validate textbox to support only, but I want to allow OemMinus (-) also how can I do this?
private void card_No_KeyDown(object sender, KeyEventArgs e)
{
nonNumberEntered = false;
// Determine whether the keystroke is a number from the top of the keyboard.
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
// Determine whether the keystroke is a number from the keypad.
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9 &&
e.KeyCode == Keys.Oemplus)
{
// Determine whether the keystroke is a backspace.
if (e.KeyCode != Keys.Back)
{
// A non-numerical keystroke was pressed.
// Set the flag to true and evaluate in KeyPress event.
nonNumberEntered = true;
}
}
}
}
private void card_No_KeyPress(object sender, KeyPressEventArgs e)
{
if (nonNumberEntered == true)
{
MessageBox.Show("not allowed");
e.Handled = true;
}
}
You could handle the KeyPress event like this
private void card_No_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsNumber(e.KeyChar) && e.KeyChar != '-' && e.KeyChar != (char)Keys.Back)
e.Handled = true;
}
But that won't prevent the user from copy pasting an invalid value so you can also handle the TextChanged event.
private void card_No_TextChanged(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(card_No.Text))
{
if (Regex.Matches(card_No.Text, #"(-|\d)").Count != card_No.Text.Length)
{
//pasted an invalid value
MessageBox.Show("Invalid value entered");
}
}
}
private void card_No_KeyPress(object sender, KeyPressEventArgs e)
{
var textBox = sender as TextBox;
//handels integers, decimal numbers and OemMinus (-) character
if (((!char.IsControl(e.KeyChar))
&& (!char.IsDigit(e.KeyChar))
&& (e.KeyChar != '-')
) || (textBox != null
&& (e.KeyChar != '.'
&& (textBox.Text.IndexOf('.') > -1))))
e.Handled = true;
if (e.Handled)
MessageBox.Show(#"not allowed");
}
//prevent copy and past and delete pasted text
private void card_No_TextChanged(object sender, EventArgs e)
{
if (card_No.Text.Length >0)
{
if (Regex.Matches(card_No.Text, #"(-|\d)").Count != card_No.Text.Length)
{
if (!Clipboard.ContainsText()) return;
var txt = Clipboard.GetText();
if (card_No.Text.Contains(txt))
{
int ind = card_No.Text.IndexOf(txt, System.StringComparison.Ordinal);
var text = card_No.Text.Substring(0, ind);
card_No.Text = text;
MessageBox.Show(#"not allowed");
}
else if (txt.Contains(card_No.Text))
{
int ind = txt.IndexOf(card_No.Text, System.StringComparison.Ordinal);
var text = txt.Substring(0, ind);
card_No.Text = text;
MessageBox.Show(#"not allowed");
}
}
}
}
Related
I must capitalize first letter of every word but with keypress event using C#. Right now every letter in the textbox gets capitalized, I added the code I use. I cant figure out how to capitalize just the first letter, or what am I doing wrong. Can you help me?
private void txt_name_KeyPress(object sender, KeyPressEventArgs e)
{
e.KeyChar = (e.KeyChar.ToString()).ToUpper().ToCharArray()[0];
}
You will need to keep track of previous key presses if you must go this route:
private char PreviousChar;
private void txt_name_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsWhiteSpace(PreviousChar) || PreviousChar == '\0')
{
e.KeyChar = Char.ToUpper(e.KeyChar);
}
PreviousChar = e.KeyChar;
}
I got by using Keydown
private void tbxName_KeyDown(object sender, KeyEventArgs e)
{
if (tbxName.Text.Length == 0 || tbxName.SelectedText.Length == tbxName.Text.Length)
{
if ((e.Key >= Key.A) && (e.Key <= Key.Z))
{
tbxName.Text = e.Key.ToString().ToUpper();
tbxName.SelectionStart = tbxName.Text.Length;
e.Handled = true;
}
}
if (tbxName.Text.Length > 0)
{
int selectionStart = tbxName.SelectionStart;
string character = tbxName.Text.Substring(selectionStart - 1, 1);
if (character.Trim() == string.Empty)
{
if ((e.Key >= Key.A) && (e.Key <= Key.Z))
{
tbxName.Text = tbxName.Text.Insert(selectionStart, e.Key.ToString().ToUpper());
tbxName.SelectionStart = selectionStart + 1;
e.Handled = true;
}
}
}
if (e.Key == Key.Enter || e.Key == Key.Tab)
{
if (tbxName.Text.Length > 2)
{
tbxDegree.Focus();
if (e.Key == Key.Tab)
e.Handled = true;
}
else
{
MessageBox.Show("Kindly verify the Name Entered");
tbxName.Focus();
}
}
}
I have textbox and when i create that form i pass some values and then i prevent user to input some things into textbox based on passed values with this code:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!brojevi && char.IsDigit(e.KeyChar))
{
e.Handled = true;
return;
}
if (!slova && char.IsLetter(e.KeyChar))
{
e.Handled = true;
return;
}
if (!znakovi && char.IsPunctuation(e.KeyChar) || !znakovi && char.IsSymbol(e.KeyChar))
{
e.Handled = true;
return;
}
if (!razmak && char.IsSeparator(e.KeyChar))
{
e.Handled = true;
return;
}
if (maxKaraktera != -1 && (textBox1.Text.Length + 1) > maxKaraktera)
{
e.Handled = true;
return;
}
if (String.IsNullOrWhiteSpace(textBox1.Text))
{
return;
}
if (maxBroj != -1 && Convert.ToDouble(textBox1.Text) > maxBroj)
{
e.Handled = true;
return;
}
}
Problem is that i enabled brojevi and set maxBroj to 10
Now when i try typing some char, it checks and see that slova is not true, set e.Handled = true and return and in my textbox that char is not imputed which is ok.
But when i try inserting number which is greater than 10 (let's say 12), it goes to if statement where it checks if(maxBroj != -1 && Convert.ToDoube(textBox1.Text) > maxBroj) and it enters it, set e.Handled = true and return but number is implemented in textbox.
Why this happens?
EDIT: Code from creating form and form that has textbox
Creating from:
MessageBoxWithValue msg = new MessageBoxWithValue("Unesite kolicinu", "Unesite zeljenu kolicinu. Maksimum: " + aa.maxKolicina.ToString());
msg.brojevi = true;
msg.maxBroj = aa.maxKolicina;
msg.ShowDialog();
if(msg.DialogResult == DialogResult.OK)
{
kol = Convert.ToDouble(msg.returnValue);
}
else
{
return;
}
Here is MessageBoxWithValue form:
public partial class MessageBoxWithValue : Form
{
public bool brojevi = false;
public bool slova = false;
public bool znakovi = false;
public bool razmak = false;
public double maxBroj = -1;
public int maxKaraktera = -1;
public string returnValue;
public MessageBoxWithValue(string naslov, string opis)
{
InitializeComponent();
this.Text = naslov;
label1.Text = opis;
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!brojevi && char.IsDigit(e.KeyChar))
{
e.Handled = true;
return;
}
if (!slova && char.IsLetter(e.KeyChar))
{
e.Handled = true;
return;
}
if (!znakovi && char.IsPunctuation(e.KeyChar) || !znakovi && char.IsSymbol(e.KeyChar))
{
e.Handled = true;
return;
}
if (!razmak && char.IsSeparator(e.KeyChar))
{
e.Handled = true;
return;
}
if (maxKaraktera != -1 && (textBox1.Text.Length + 1) > maxKaraktera)
{
e.Handled = true;
return;
}
if (String.IsNullOrWhiteSpace(textBox1.Text))
{
return;
}
if (maxBroj != -1 && Convert.ToDouble(textBox1.Text) > maxBroj)
{
e.Handled = true;
return;
}
}
private void button2_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
{
Uspesno();
}
}
private void button1_Click(object sender, EventArgs e)
{
Uspesno();
}
private void Uspesno()
{
this.DialogResult = DialogResult.OK;
returnValue = textBox1.Text;
}
}
But when i try inserting number which is greater than 10 (let's say 12), it goes to if statement where it checks if(maxBroj != -1 && Convert.ToDoube(textBox1.Text) > maxBroj) and it enters it, set e.Handled = true and return but number is implemented in textbox.
I hope I've got your issue right. You are trying to filter numbers by their values (e.g. maxBroj is set to 10) and you are expecting
if (maxBroj != -1 && Convert.ToDouble(textBox1.Text) > maxBroj)
{
e.Handled = true;
return;
}
not to allow entering a number >10. Unfortunately this will not work as intended, since textBox1.Text won't be set until the KeyPress event handler has finished.
Let's say you are entering 14. When the first KeyPress event is raised (1), textBox1.Text is empty. You are returning from
if (String.IsNullOrWhiteSpace(textBox1.Text))
{
return;
}
Afterwards textBox1.Text is set to "1". Then the second KeyPress event is raised. textBox1.Text is "1", hence the method won't enter the block
if (maxBroj != -1 && Convert.ToDouble(textBox1.Text) > maxBroj)
{
e.Handled = true;
return;
}
Afterwards textBox1.Text will be set to "14", but this is too late for your validation.
You'll have to calculate the expected new value. Please see this question on how to insert the new character in the existing string.
I have a textbox which user should type a price in it.
I need to prevent continue typing if price starts with 0.
For example user can not type "000" or "00009".
I tried this on KeyPress, but nothing!
if (txt.Text.StartsWith("0"))
return; Or e.Handeled = true;
try this:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
//only allow digit and (.) and backspace
if ((e.KeyChar < '0' || e.KeyChar > '9') && e.KeyChar != '\b' && e.KeyChar != '.')
{
e.Handled = true;
}
var txt = sender as TextBox;
//only allow one dot
if (txt.Text.Contains('.') && e.KeyChar == (int)'.')
{
e.Handled = true;
}
//if 0, only allow 0.xxxx
if (txt.Text.StartsWith("0")
&& !txt.Text.StartsWith("0.")
&& e.KeyChar != '\b'
&& e.KeyChar != (int)'.')
{
e.Handled = true;
}
}
You could use the TextChanged-event for this.
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (this.textBox1.Text == "0") this.textBox1.Text = "";
}
This will only work, if the TextBox is empty on startup.
I solved it Myself:
private void txtPrice_KeyPress(object sender, KeyPressEventArgs e)
{
if (txtPrice.Text.StartsWith("0") && !char.IsControl(e.KeyChar))
{
e.Handled = true;
return;
}
}
I have a textbox with a OnKeyPress event. In this textbox I wish to input only numbers, and for some specific letters like t or m, I would want to execute a code without that letter being typed in the textbox. Small sample of what I am trying to do:
//OnKeyPressed:
void TextBox1KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.T || e.KeyCode == Keys.M) Button1Click(this, EventArgs.Empty);
}
This unfortunately does not prevent the input of the letter..
Set the SuppressKeyPress property from KeyEventArgs to true, like below:
private void TextBox1KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.T || e.KeyCode == Keys.M)
{
e.SuppressKeyPress = true;
Button1Click(this, EventArgs.Empty);
}
}
You could always run the TryParse on the keyDown event so as to validate as the data gets entered. It saves the user an additional UI interaction.
private void TextBox1KeyDown(object sender, KeyEventArgs e)
{
int i;
string s = string.Empty;
s += (char)e.KeyValue;
if (!(int.TryParse(s, out i)))
{
e.SuppressKeyPress = true;
}
else if(e.KeyCode == Keys.T || e.KeyCode == Keys.M)
{
e.SuppressKeyPress = true;
Button1Click(this, EventArgs.Empty);
}
}
I need to make datagridview that only accept the numeric value for specific column only in keypress event. Is there any best way to do this?
Add an event of EditingControlShowing
In EditingControlShowing, check that if the current cell lies in the desired column.
Register a new event of KeyPress in EditingControlShowing(if above condition is true).
Remove any KeyPress event added previously in EditingControlShowing.
In KeyPress event, check that if key is not digit then cancel the input.
Example:
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyPress -= new KeyPressEventHandler(Column1_KeyPress);
if (dataGridView1.CurrentCell.ColumnIndex == 0) //Desired Column
{
TextBox tb = e.Control as TextBox;
if (tb != null)
{
tb.KeyPress += new KeyPressEventHandler(Column1_KeyPress);
}
}
}
private void Column1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
You must use DataGridView.CellValidating Event like this :
private void dataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
if (e.ColumnIndex == 1) // 1 should be your column index
{
int i;
if (!int.TryParse(Convert.ToString(e.FormattedValue), out i))
{
e.Cancel = true;
label1.Text ="please enter numeric";
}
else
{
// the input is numeric
}
}
}
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyPress -= new KeyPressEventHandler(Column1_KeyPress);
if (dataGridView1.CurrentCell.ColumnIndex == 4) //Desired Column
{
TextBox tb = e.Control as TextBox;
if (tb != null)
{
tb.KeyPress += new KeyPressEventHandler(Column1_KeyPress);
}
}
}
private void Column1_KeyPress(object sender, KeyPressEventArgs e)
{
// allowed only numeric value ex.10
//if (!char.IsControl(e.KeyChar)
// && !char.IsDigit(e.KeyChar))
//{
// e.Handled = true;
//}
// allowed numeric and one dot ex. 10.23
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;
}
}
The answer given is excellent unless you require decimal places as others have pointed out.
In this event you need to extend the validation, add the using and vars below to get a culture variable value for the decimal separator
using System.Globalization;
NumberFormatInfo nfi = Thread.CurrentThread.CurrentCulture.NumberFormat;
char decSeperator;
decSeperator = nfi.CurrencyDecimalSeparator[0];
Extend the validation to:
if (!char.IsControl(e.KeyChar) && !(char.IsDigit(e.KeyChar)
| e.KeyChar == decSeperator))
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == decSeperator
&& (sender as TextBox).Text.IndexOf(decSeperator) > -1)
{
e.Handled = true;
}
Private WithEvents txtNumeric As New DataGridViewTextBoxEditingControl
Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
txtNumeric = CType(e.Control, DataGridViewTextBoxEditingControl)
End Sub
Private Sub txtNumeric_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtNumeric.KeyPress
If (DataGridView1.CurrentCell.ColumnIndex > 0) Then
If (Not Char.IsControl(e.KeyChar) And Not Char.IsDigit(e.KeyChar) And Not e.KeyChar = ".") Then
e.Handled = True
Else
'only allow one decimal point
If (e.KeyChar = "." And txtNumeric.Text.Contains(".")) Then
e.Handled = True
End If
End If
End If
End Sub
You could also try this way, with accept decimals character
private void Column1_KeyPress(object sender, KeyPressEventArgs e)
{
//allow number, backspace and dot
if (!(char.IsDigit(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == '.'))
{
e.Handled = true;
}
//allow only one dot
if (e.KeyChar == '.' && (sender as TextBox).Text.Contains("."))
{
e.Handled = true;
}
}
I was doing a matrix calculator and was using two DataGridView objects. Here's a code that worked for me. I took the very first comment from this post and changed it a bit.
//Adding characters to a cell
private void dataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control != null)
{
e.Control.KeyPress += new KeyPressEventHandler(Column1_KeyPress);
Console.WriteLine(e.Control.Text);
}
}
//Handling presses for minus dot and numbers
private void Column1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '-' && e.KeyChar != '.')
e.Handled = true;
if (e.KeyChar == '.')
{
if (((DataGridViewTextBoxEditingControl)sender).Text.Length == 0)
e.Handled = true;
if (((DataGridViewTextBoxEditingControl)sender).Text.Contains('.'))
e.Handled = true;
}
if (e.KeyChar == '-')
{
if (((DataGridViewTextBoxEditingControl)sender).Text.Length != 0)
e.Handled = true;
if (((DataGridViewTextBoxEditingControl)sender).Text.Contains('-'))
e.Handled = true;
}
}