How remove characters minus (-) in middle or end in string c# - c#

I want delete one character minus - that the user press in a textbox. I validate that the user has not pressed the minus key twice with event key_press:
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.') && (e.KeyChar != '-'))
{
e.Handled = true;
}
// only allow one minus -
if (e.KeyChar == '-' && ((sender as TextBox).Text.IndexOf('-') > -1))
{
e.Handled = true;
}
the problem is when the user presses the minus sign key in middle or end of the string. For example:
1000.-00 <--- Invalid
2000.00- <--- Invalid
-1000.00 <--- valid
How can I ensure the minus sign is beginning the contents of the text box?

if (e.KeyChar == '-' && ((sender as TextBox).Text.Length > 1))
This allows only one dash at the beginning. Maybe you need to trim the Text first...

use it like this
declare a variable at class level like this int minusCount=0;
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.') && (e.KeyChar != '-'))
{
e.Handled = true;
}
// only allow one minus -
//put condition if it is zero than only allow one minus sign
if (e.KeyChar == '-' && ((sender as TextBox).Text.IndexOf('-') > -1) && minusCount==0)
{
e.Handled = true;
//over here increment that variable
minusCount = minusCount+1;
//for handling it in middle other than zero position
if(textbox.Text.IndexOf("-")>1)
{
textbox.Text=textbox.Text.Replace("-","");
}
}

The problem with your second if is that at the time when you do the check the sender (i.e. the TextBox) does not have the minus yet. You should construct the text with the minus first, then validate it to make a decision:
if (e.KeyChar == '-') {
var tb = sender as TextBox;
// Obtain the text after the modification
var modifiedText = tb.Text.Insert(tb.SelectionStart, "-");
// There will be at least one '-' in the text box - the one you just inserted.
// Its position must be 0, otherwise the string is invalid:
e.Handled = modifiedText.LastIndexOf("-") != 0;
}

Related

How I can limit the introduced digits in the cell of the datagridview?

I want to create a datagridview that only accept numbers (Integers or doubles). When the number is double, I only want to save 2 digits after the point. (E.g. 1.22) and automatically change the cell. I create an event to make this.
I was able to get a working event but when I put the number with 2 digits after the point, the last digit doesn’t appear in the cell and the cell change.
When I’m debugging with a breakpoint in the line “dgvDatos[column, row].Value = txtInCell;” . The variable txtInCell (is used to see what is written in the cell ) has the correct/complete value .
void dText_KeyPress(object sender, KeyPressEventArgs e)
{
bool dot;
if (txtInCell.Contains(".") == true)
dot = true;
else
dot = false;
//Only accept numbers
if (Char.IsDigit(e.KeyChar) || e.KeyChar == '.' || e.KeyChar == '-')
{
if (e.KeyChar == '.')
if (!dot)
{
txtInCell += e.KeyChar;
e.Handled = false;
}
else
e.Handled = true;
else
txtInCell += e.KeyChar;
if (txtInCell.Contains("."))
{
int row = dgvDatos.CurrentCell.RowIndex;
int column = dgvDatos.CurrentCell.ColumnIndex;
string[] elements = txtInCell.Split('.');
if (elements[1].Length > 1)
{
dgvDatos[column, row].Value = txtInCell;
dgvDatos.CurrentCell = this.dgvDatos[column + 1, row];
}
}
}
else if (Char.IsControl(e.KeyChar)) //Use backspace as control
{
if (e.KeyChar == '\b')
txtInCell = txtInCell.Remove(txtInCell.Length - 1);
e.Handled = false;
}
else
{
//all the other keys are disabled
e.Handled = true;
}
}
Use validate event
dataGridView1.CellValidating += (s, eargs) => eargs.Cancel = !new Regex(#"^\d*(.\d|.\d\d)$").IsMatch(eargs.FormattedValue.ToString());
You can also give a tooltip about why you are not allowing the user to enter the value like you cannot enter more than two decimal digits etc you can also add some coloring flashing to add more spice

how to validate a textbox for specific pattern in Windows form c#

I want to validate a Textbox for a specific input pattern that contains Number, dot & plus singh only.
for example.
50.4+50.6+60.7+80.4
etc...
I want user can input only in this pattern because at last I want to plus this all value separated by plus singh. So it is necessary for a user that he follow this pattern.
please any body give me solution for this.
I am working in c# Windows form application.
Using a KeyPress event:
private void CheckInput(object sender, KeyPressEventArgs e)
{
// Make sure only digits, . and +
if (!char.IsDigit(e.KeyChar) && e.KeyChar != '.' && e.KeyChar != '+')
{
e.Handled = true;
}
// Make sure . is in correct places only
else if (e.KeyChar == '.')
{
for (int i = textBox1.SelectionStart - 1; i >= 0; i--)
{
if (textBox1.Text[i] == '.')
{
e.Handled = true;
break;
}
else if (textBox1.Text[i] == '+') break;
}
}
// Make sure character before + is a digit
else if (e.KeyChar == '+'
&& !char.IsDigit(textBox1.Text[textBox1.SelectionStart - 1]))
{
e.Handled = true;
}
}

TextBox with Numeric Input

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;

textbox validation for allow one " . " value c#

I want textbox validation for allowing only one . value and only numbers. Means my textbox value should take only numerics and one . value. Value should be like 123.50.
I am using a code for adding .oo or .50 value at end of my value.
My code is
double x;
double.TryParse(tb.Text, out x);
tb.Text = x.ToString(".00");
It is taking all the keys from keyboard, but I want to take only numbers and one . value.
Add a Control.KeyPress event handler for your textbox.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)) //bypass control keys
{
int dotIndex = textBox1.Text.IndexOf('.');
if (char.IsDigit(e.KeyChar)) //ensure it's a digit
{ //we cannot accept another digit if
if (dotIndex != -1 && //there is already a dot and
//dot is to the left from the cursor position and
dotIndex < textBox1.SelectionStart &&
//there're already 2 symbols to the right from the dot
textBox1.Text.Substring(dotIndex + 1).Length >= 2)
{
e.Handled = true;
}
}
else //we cannot accept this char if
e.Handled = e.KeyChar != '.' || //it's not a dot or
//there is already a dot in the text or
dotIndex != -1 ||
//text is empty or
textBox1.Text.Length == 0 ||
//there are more than 2 symbols from cursor position
//to the end of the text
textBox1.SelectionStart + 2 < textBox1.Text.Length;
}
}
You may do it through designer or in your constructor like this:
public Form1()
{
InitializeComponent();
//..other initialization
textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
}
I have also added several checks to ensure, that you could insert digits not only in the end of the text, but in any position. Same with a dot. It controls that you have not more than 2 digits to the right from the dot. I've used TextBox.SelectionStart Property to get the position of the cursor in the textbox. Check this thread for more info about that: How do I find the position of a cursor in a text box?
Simplly in keyPress event of your textBox you could do this ...
e.Handled = !char.IsDigit(e.KeyChar)&&(e.KeyChar != '.') && !char.IsControl(e.KeyChar);
if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
{
e.Handled = true;
}
try this one
private void textBox1_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 == '.'
&& textBox1.Text.IndexOf('.') > -1)
e.Handled = true;
}
try this code and just replace what you want input type 'validinpu' string.
try
{
short charCode = (short)Strings.Asc(e.KeyChar);
string validinput = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-0123456789 .";
if (Strings.InStr(validamt, Conversions.ToString(Strings.Chr(charCode)), Microsoft.VisualBasic.CompareMethod.Binary) == 0)
{
charCode = 0;
}
if (charCode == 0)
{
e.Handled = true;
}
}
Another example ,
private void txtPrice_KeyPress(object sender, KeyPressEventArgs e)
{
// To disallow typing in the beginning writing
if (txtPrice.Text.Length == 0)
{
if (e.KeyChar == '.')
{
e.Handled = true;
}
}
if (!char.IsDigit(e.KeyChar) && e.KeyChar != 8 && e.KeyChar != 46)
{
e.Handled = true;
}
if (e.KeyChar == '.' && txtPrice.Text.IndexOf('.') > -1)
{
e.Handled = true;
}
}
Also try this short one
e.Handled = (!(e.KeyChar == (char)Keys.Back || e.KeyChar == '.')); //allow dot and Backspace
e.Handled = (e.KeyChar == '.' && TextBox1.Text.Contains(".")); //allow only one dot
this example only allow one dot and backspace
if (textBox.Text!="")
{
string txt = textBox.Text;
if (e.KeyChar.ToString().Any(Char.IsNumber) || e.KeyChar == '.')
{
textBox.Text = rate;
}
else
{
MessageBox.Show("Number Only", "Warning");
textBox.Text = "";
}
}
My tested code
if(e.KeyChar.Equals('\b'))
{
e.Handled = false;
}
else
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
{
e.Handled = true;
}
else
// only allow one decimal point
if (e.KeyChar == '.'
&& textBox1.Text.IndexOf('.') > -1)
{
e.Handled = true;
}

Validation-Textboxes allowing only decimals

I am using following code for validating textbox.
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = SingleDecimal(sender, e.KeyChar);
}
public bool SingleDecimal(System.Object sender, char eChar)
{
string chkstr = "0123456789.";
if (chkstr.IndexOf(eChar) > -1 || eChar == Constants.vbBack)
{
if (eChar == ".")
{
if (((TextBox)sender).Text.IndexOf(eChar) > -1)
{
return true;
}
else
{
return false;
}
}
return false;
}
else
{
return true;
}
}
Problem is Constants.vbBack is showing error.If i didnt use Constants.vbBack,backspace is not workimg.What alteration can i make to work backspace.Can anybody help?
here is the code I would use...
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// allows 0-9, backspace, and decimal
if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46))
{
e.Handled = true;
return;
}
// checks to make sure only 1 decimal is allowed
if (e.KeyChar == 46)
{
if ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1)
e.Handled = true;
}
}
You can make a method to check if it's a number.
Instead of checking for the . as a decimal separator you should get it from CurrentCulture object as it could be another character depending on where in the world you are.
public bool isNumber(char ch, string text)
{
bool res = true;
char decimalChar = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
//check if it´s a decimal separator and if doesn´t already have one in the text string
if (ch == decimalChar && text.IndexOf(decimalChar) != -1)
{
res = false;
return res;
}
//check if it´s a digit, decimal separator and backspace
if (!Char.IsDigit(ch) && ch != decimalChar && ch != (char)Keys.Back)
res = false;
return res;
}
Then you can call the method in the KeyPress event of the TextBox:
private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if(!isNumber(e.KeyChar,TextBox1.Text))
e.Handled=true;
}
create a component inherited from textbox and use this code:
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.' && Text.IndexOf('.') > -1)
{
e.Handled = true;
}
base.OnKeyPress(e);
}
Here is a Vb.Net version for #Eclipsed4utoo's answer
If (((Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57) And Asc(e.KeyChar) <> 8 And Asc(e.KeyChar) <> 46)) Then
e.Handled = True
Exit Sub
End If
' checks to make sure only 1 decimal is allowed
If (Asc(e.KeyChar) = 46) Then
If (sender.Text.IndexOf(e.KeyChar) <> -1) Then
e.Handled = True
End If
End If
This codes for decimals. If you want to use float also, you just use double insteat int
And it will be delete automaticaly last wrong charachters
private void txt_miktar_TextChanged(object sender, TextChangedEventArgs e)
{
if ((sender as TextBox).Text.Length < 1)
{
return;
}
try
{
int adet = Convert.ToInt32((sender as TextBox).Text);
}
catch
{
string s = "";
s = (sender as TextBox).Text;
s = s.Substring(0, s.Length - 1);
(sender as TextBox).Text = s;
(sender as TextBox).Select(s.Length, s.Length);
}
}
How about using the example from MSDN?
Are u using the '.' as decimal seperator? if so than I don't know why you are using
if (((TextBox)sender).Text.IndexOf(eChar) > -1)
Here some code from my app. It handle one more case as will related to selection
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (e.KeyChar == '\b')
return;
string newStr;
if (SelectionLength > 0)
newStr = Text.Remove(SelectionStart, SelectionLength);
newStr = Text.Insert(SelectionStart, new string(e.KeyChar, 1));
double v;
//I used regular expression but you can use following.
e.Handled = !double.TryParse(newStr,out v);
base.OnKeyPress(e);
}
here regex expression if like to use them instead of that easy type parsing
const string SIGNED_FLOAT_KEY_REGX = #"^[+-]?[0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]*)?$";
const string SIGNED_INTEGER_KEY_REGX = #"^[+-]?[0-9]*$";
const string SIGNED_FLOAT_REGX = #"^[+-]?[0-9]*(\.[0-9]+)?([Ee][+-]?[0-9]+)?$";
const string SIGNED_INTEGER_REGX = #"^[+-]?[0-9]+$";
I believe this is the perfect solution as it not only confines the text to numbers, only a leading minus sign, and only one decimal point, but it allows the replacement of selected text if it contains a decimal point. The selected text still cannot be replaced by a decimal point if there is a decimal point in the non-selected text. It allows a minus sign only if it's the first character or if the entire text is selected.
private bool DecimalOnly_KeyPress(TextBox txt, bool numeric, KeyPressEventArgs e)
{
if (numeric)
{
// only allow numbers
if (!char.IsDigit(e.KeyChar) && e.KeyChar != Convert.ToChar(Keys.Back))
return true;
}
else
{
// allow a minus sign if it's the first character or the entire text is selected
if (e.KeyChar == '-' && (txt.Text == "" || txt.SelectedText == txt.Text))
return false;
// if a decimal point is entered and if one is not already in the string
if ((e.KeyChar == '.') && (txt.Text.IndexOf('.') > -1))
{
if (txt.SelectedText.IndexOf('.') > -1)
// allow a decimal point if the selected text contains a decimal point, that is the
// decimal point replaces the selected text
return false;
else
// don't allow a decimal point if one is already in the string and the selected text
// doesn't contain one
return true;
}
// if the entry is not a digit
if (!Char.IsDigit(e.KeyChar))
{
// if it's not a decimal point and it's not a backspace then disallow
if ((e.KeyChar != '.') && (e.KeyChar != Convert.ToChar(Keys.Back)))
{
return true;
}
}
}
// allow only a minus sign but only in the beginning, only one decimal point, any digit, a
// backspace, and replace selected text.
return false;
}
Here is a vb.net version that allows negative decimal figure, prevent copy and paste while making sure the negative sign is not in the middle of the text or the decimal point not at the beginning of the text
Public Sub Numeric(textControl As Object, e As KeyPressEventArgs)
Dim Index As Int32 = textControl.SelectionStart
Dim currentLine As Int32 = textControl.GetLineFromCharIndex(Index)
Dim currentColumn As Int32 = Index - textControl.GetFirstCharIndexFromLine(currentLine)
Dim FullStop As Char
FullStop = "."
Dim Neg As Char
Neg = "-"
' if the '.' key was pressed see if there already is a '.' in the string
' if so, dont handle the keypress
If e.KeyChar = FullStop And textControl.Text.IndexOf(FullStop) <> -1 Then
e.Handled = True
Return
End If
'If the '.' is at the begining of the figures, prevent it
If e.KeyChar = FullStop And currentColumn <= 0 Then
e.Handled = True
Return
End If
' if the '-' key was pressed see if there already is a '-' in the string
' if so, dont handle the keypress
If e.KeyChar = Neg And textControl.Text.IndexOf(Neg) <> -1 Then
e.Handled = True
Return
End If
'If the '-' is in the middle of the figures, prevent it
If e.KeyChar = Neg And currentColumn > 0 Then
e.Handled = True
Return
End If
' If the key aint a digit
If Not Char.IsDigit(e.KeyChar) Then
' verify whether special keys were pressed
' (i.e. all allowed non digit keys - in this example
' only space and the '.' are validated)
If (e.KeyChar <> Neg) And (e.KeyChar <> FullStop) And (e.KeyChar <> Convert.ToChar(Keys.Back)) Then
' if its a non-allowed key, dont handle the keypress
e.Handled = True
Return
End If
End If
End Sub
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
Numeric(sender, e)
End Sub
try this with asp:RegularExpressionValidator controller
<asp:RegularExpressionValidator ID="rgx"
ValidationExpression="[0-9]*\.?[0-9][0-9]" ControlToValidate="YourTextBox" runat="server" ForeColor="Red" ErrorMessage="Decimals only!!" Display="Dynamic" ValidationGroup="lnkSave"></asp:RegularExpressionValidator>

Categories

Resources