Allow only Numbers and Hyphen declaring a negative number in a textbox - c#

I tried to get textboxes to only allow numbers and a hyphen declaring a negative number however i researched and tried to replicate what i found and it doesn't work. maybe im missing something but i have no clue about Regex so maybe its wrong. but it doesn't update and accepts letters and other characters
Regex reg = new Regex(#"^[0-9-]*$");
bool textChangedByKey;
string lastText;
private void Team1Q1_KeyPress(object sender, KeyPressEventArgs e)
{
TextBox senderTB = sender as TextBox;
if (char.IsControl(e.KeyChar)) return;
if (!reg.IsMatch(senderTB.Text.Insert(senderTB.SelectionStart, e.KeyChar.ToString()) + "1"))
{
e.Handled = true;
return;
}
textChangedByKey = true;
}
private void Team1Q1_TextChanged(object sender, EventArgs e)
{
OnTeamInfoChanged();
TextBox senderTB = sender as TextBox;
if (!textChangedByKey)
{
if (!reg.IsMatch(senderTB.Text))
{
return;
}
}
else
{
textChangedByKey = false;
lastText = senderTB.Text;
}
}

Changing the Regex pattern to ^-?[0-9]*$ would only allow a single hyphen, and only at the start of the input.
Wiring up the KeyPress event handler in the designer class like so should cause disallowed characters to get filtered out:
this.Team1Q1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.Team1Q1_KeyPress);`

Related

Guidance text when typing in a text box in c#

I'm a starter at this so not sure if this is simple or crazly hard but what i would like is after 6 characters in a text box a - to appear and then they continue typing abit like when you do a license number in windows and it autopolutes the field as you go.
Add an event KeyPress to your textbox, so every time when you change text it will add '-' if needed. Something like this:
private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsControl(e.KeyChar) == false)
{
var tb = (sender as TextBox);
var text = tb.Text;
var blocks = text.Split('-');
var lastBlock = blocks.Last();
if (lastBlock.Length == 6)
{
tb.Text += "-";
tb.SelectionStart = tb.Text.Length;
}
}
}
There is a bug although with entering '-', as it is used as a separator.

How to restrict user from entering specific chars (xml invalid characters) in textbox?

I have this problem with TextBox. User enters text/string in the TextBox and this string is exported as an value of attribute in the xml file. Is there some way how can I disable the user to enter (type+paste) forbidden (for xml format) characters, like the symbol for Euro €?
instead of restricting user you can filter out all the characters that you don't want before passing to your xml.
string textToPAss = ReplaceInvalidCharacters(yourTextbox.Text);
public string ReplaceInvalidCharacters(string toReplace)
{
toReplace = toReplace.Replace("€","");
//similarly do for all others unwanted characters
return toReplace;
}
Handle the KeyPress event
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '€')
e.Handled = true;
}
invalid XML characters has their valid XML equivalent. so if you can convert input to a valid XML then final result will be valid XML.
inputText = SecurityElement.Escape(inputText);
Ref :SecurityElement.Escape
This will block the letter a from being typed into the textbox.
private void textBox1_TextChanged(object sender, EventArgs e)
{
int pos = (sender as TextBox).Text.IndexOf("a");
(sender as TextBox).Text = (sender as TextBox).Text.Replace("a", "");
if (pos!= -1)
(sender as TextBox).Select(pos, 0);
}
but as, Somesh Mukherjee, said rather Filter invalid chars out later. a simple String.Replace() will do the trick.
Here is an code example what you're looking for:
class MyTextBox : TextBox
{
protected override void WndProc(ref Message m)
{
// Trap WM_PASTE:
if (m.Msg == 0x302 && Clipboard.ContainsText())
{
var removedInvalid = from c in Clipboard.GetText()
where XmlConvert.IsXmlChar(c)
select c;
SelectedText = new string(removedInvalid.ToArray());
return;
}
base.WndProc(ref m);
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (!XmlConvert.IsXmlChar(e.KeyChar))
e.Handled = true;
base.OnKeyPress(e);
}
}
The above prevents the user to either stroke or paste invalid XML characters into the text box.

unable to clear a textbox data

I'm not able to delete textbox data with the code below
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if(char.IsDigit(e.KeyChar)==false)
{
count++;
}
if (count == 1)
{
textBox1.Text = ("");
count = 0;
}
}
tried using clear method as well the alphabet i entered stays in the textbox and when i type any key it get overwritten but i want the textbox to be empty the second time and the prev data to be removed
you just need to say you've handled the event:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar) == false)
{
count++;
}
if (count == 1)
{
textBox1.Text = ("");
count = 0;
e.Handled = true; // this bit fixes it
}
}
use textBox1.Text = ""; OR textBox1.clear();
This will clear your textbox.
You are doing it wrong. You can just paste in a bunch of letters with Ctrl+V. Delete the KeyDown event and create a TextChanged event. This code should accomplish what you are attempting. Please tell me if there is any more details and I will add to my answer.
private void textBox1_TextChanged(object sender, EventArgs e)
{
foreach (char c in textBox1.Text)
if (!char.IsDigit(c)) { textBox1.Clear(); break; }
}
Add this to your text box key press event your problem will be solved
e.handle = true;

Detect decimal separator

I have to detect decimal separator in current windows setting. Im using visual studio 2010, windows form. In particular, if DecimalSeparator is comma, if user input dot in textbox1, I need show zero in textbox2.
I tryed with this code, but not works:
private void tbxDaConvertire_KeyPress(object sender, KeyPressEventArgs e)
{
string uiSep = CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator;
if (uiSep.Equals(","))
{
while (e.KeyChar == (char)46)
{
tbxConvertito.Text = "0";
}
}
}
I have tryed also this code, but not work:
private void tbxDaConvertire_KeyPress(object sender, KeyPressEventArgs e)
{
string uiSep = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
if (uiSep.Equals(","))
{
if (e.KeyChar == (char)46)
{
tbxConvertito.Text = "0";
}
}
}
Solution:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
char a = Convert.ToChar(Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator);
if (e.KeyChar == a)
{
e.Handled = true;
textBox1.Text = "0";
}
}
That way, when you hit . or , you will have a 0 in your TextBox.
EDIT:
If you want to insert a 0 everytime you hit the decimal separator, this is the code:
char a = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
if (e.KeyChar == a)
{
e.KeyChar = '0';
}
Actually you should be using
CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
instead of
CultureInfo.CurrentUICulture.NumberFormat.NumberDecimalSeparator
Using the second one gives you the OS default settings, which might be different then user Regional Locales for particular user account logged to this PC.
Credits to berhir and Grimm for pointing out the [docs]
You shouldn't use a while loop, I think it will freeze the application, use if instead, the problem might be here

To Disable Negative Values Inside a TextBox

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

Categories

Resources