I want to limit user to type just numbers in TextBox.
I add this code In keypress Event:
private void txtPartID_KeyPress(object sender, KeyPressEventArgs e)
{
if (((e.KeyChar >= '0') && (e.KeyChar <= '9')) == false)
{
e.Handled = true;
}
}
but after that BackSpace key don't work for this TextBox. How can I change this?
You can check for backspace using this,
if(e.KeyChar == '\b')
And better way to check only for numbers is
private void txtPartID_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !(Char.IsNumber(e.KeyChar) || e.KeyChar == 8);
}
private void TxtBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(Char.IsDigit(e.KeyChar) && (e.KeyChar == (char)Keys.Back)))
e.Handled = true;
}
I think you should handle both back key and delete key.
if (!(Char.IsDigit(e.KeyChar) && (e.KeyChar == (char)Keys.Back)&& (e.KeyChar == (char)Keys.Delete)))
e.Handled = true;
You can use it
private void txtColumn_KeyPress(object sender, KeyPressEventArgs e)
{
if (((e.KeyChar >= '0') && (e.KeyChar <= '9') || (e.KeyChar == (char)Keys.Back)) == false)
{
e.Handled = true;
}
}
Related
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 two buttons.
When I start my api and hit Enter then api doing code from buuton1.
How to block it?
private void frm2_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
{
}...
Doesn't work.
You can block a key by setting SuppresKeyPress to true in your event handler frm2_KeyPress:
if (e.KeyCode == Keys.Enter) {
e.SuppressKeyPress = true;
}
Please note I have changed e.KeyChar to e.KeyCode as personally I find e.KeyCode == Keys.Enter more readible than (e.KeyChar == (char)13)
You can use the KeyPressEventargs.Handled property for this.
private void frm2_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
{
e.Handled = true;
}
}
For more information, see: https://msdn.microsoft.com/en-us/library/system.windows.forms.keypresseventargs.handled(v=vs.110).aspx
I have a gridview in my C# windows application ... It allowed to be edited and I want a special cell (named "Price") to just allow number on keypress ... I use the code below for texboxes to just allow numbers ... in which event of grid view should I write this code?
private void txtJustNumber_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit((char)(e.KeyChar)) &&
e.KeyChar != ((char)(Keys.Enter)) &&
(e.KeyChar != (char)(Keys.Delete) || e.KeyChar == Char.Parse(".")) &&
e.KeyChar != (char)(Keys.Back))
{
e.Handled = true;
}
}
You can use CellValidating event of DataGridView.
private void dataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
// Validate the Price entry.
if (dataGridView1.Columns[e.ColumnIndex].Name == "Price")
{
}
}
thx guys ... I used below code and my problem resolved ...
public Form1()
{
InitializeComponent();
MyDataGridViewInitializationMethod();
}
private void MyDataGridViewInitializationMethod()
{
gvFactorItems.EditingControlShowing +=
new DataGridViewEditingControlShowingEventHandler(gvFactorItems_EditingControlShowing);
}
private void gvFactorItems_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyPress += new KeyPressEventHandler(Control_KeyPress); ;
}
private void Control_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit((char)(e.KeyChar)) &&
e.KeyChar != ((char)(Keys.Enter)) &&
(e.KeyChar != (char)(Keys.Delete) || e.KeyChar == Char.Parse(".")) &&
e.KeyChar != (char)(Keys.Back))
{
e.Handled = true;
}
}
I think you should take a look at this, it will help :-
DataGridView keydown event not working in C#
I use below code to not allowing any character except numbers in a textbox ... but it allows '.' character! I don't want it to allow dot.
private void txtJustNumber_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit((char)(e.KeyChar)) &&
e.KeyChar != ((char)(Keys.Enter)) &&
e.KeyChar != (char)(Keys.Delete) &&
e.KeyChar != (char)(Keys.Back)&&
e.KeyChar !=(char)(Keys.OemPeriod))
{
e.Handled = true;
}
}
use this:
if (!char.IsDigit((char)(e.KeyChar)) &&
e.KeyChar != ((char)(Keys.Enter)) &&
(e.KeyChar != (char)(Keys.Delete) || e.KeyChar == Char.Parse(".")) &&
e.KeyChar != (char)(Keys.Back)
)
it is because Keys.Delete's char value is 46 which is the same as '.'. I do not know why it likes this.
You could try this instead (where textBox1 would be your textbox):
// Hook up the text changed event.
textBox1.TextChanged += textBox1_TextChanged;
...
private void textBox1_TextChanged(object sender, EventArgs e)
{
// Replace all non-digit char's with empty string.
textBox1.Text = Regex.Replace(textBox1.Text, #"[^\d]", "");
}
Or
// Save the regular expression object globally (so it won't be created every time the text is changed).
Regex reg = new Regex(#"[^\d]");
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (reg.IsMatch(textBox1.Text))
textBox1.Text = reg.Replace(textBox1.Text, ""); // Replace only if it matches.
}
//This is the shortest way
private void txtJustNumber_KeyPress(object sender, KeyPressEventArgs e)
{
if(!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
try this code for your problem in keypress event :
private void txtMazaneh_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar) && (int)e.KeyChar != 8 ||(e.KeyChar= .))
e.Handled = true;
}
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;
}
}