I have 3 text-boxes in my C# Windows Form application for A, B and C respectively. Just like a simple scoring board.
What I want to do is when I press 'A' and then '1' the value in the text-box below should increment by 5 and when I press 'B' and then '1' the same should happen with the text-box below B and same as 'C'.
Just remember I don't want to use the combination keys. Below is the code for your reference:
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.A)
{
if (e.KeyCode == Keys.D1 || e.KeyCode == Keys.NumPad1)
{
int vA = int.Parse(textBox1.Text);
vA += 5;
textBox1.Text = (String)vA.ToString();
}
}
if (e.KeyCode == Keys.B)
{
if (e.KeyCode == Keys.D1 || e.KeyCode == Keys.NumPad1)
{
int vB = int.Parse(textBox2.Text);
vB += 5;
textBox2.Text = (String)vB.ToString();
}
}
}
Considering you do NOT want to use combination keys, what you want to do is something similar to this (probably clean it up a little bit).
TextBox target;
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.A)
{
target = textBox1;
}
if (e.KeyCode == Keys.B)
{
target = textBox2;
}
if (e.KeyCode == Keys.D1 || e.KeyCode == Keys.NumPad1)
{
if(target != null)
{
int vA = int.Parse(target.Text);
vA += 5;
target.Text = (String)vA.ToString();
}
}
}
We can use a member variable to keep the value of last pressed key and use that variable inside KeyUp method to check the conditions.
public partial class Form1 : Form
{
Keys lastkeyPressed = Keys.Enter;
public Form1()
{
InitializeComponent();
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (lastkeyPressed == Keys.A)
{
if (e.KeyCode == Keys.D1 || e.KeyCode == Keys.NumPad1)
{
int vA = 0;
int.TryParse(textBox1.Text, out vA);
vA += 5;
textBox1.Text = (String)vA.ToString();
}
}
if (lastkeyPressed == Keys.B)
{
if (e.KeyCode == Keys.D1 || e.KeyCode == Keys.NumPad1)
{
int vB = 0;
int.TryParse(textBox2.Text, out vB);
vB += 5;
textBox2.Text = (String)vB.ToString();
}
}
if (lastkeyPressed == Keys.C)
{
if (e.KeyCode == Keys.D1 || e.KeyCode == Keys.NumPad1)
{
int vC = 0;
int.TryParse(textBox3.Text, out vC);
vC += 5;
textBox3.Text = (String)vC.ToString();
}
}
lastkeyPressed = e.KeyCode;
}
}
Related
I am developing a winform application using c# I have successfully implemented a way to restrict textbox to two decimal places. How can I do it to one decimal place. ?
My code for two decimal places.\
private void txtHraRep_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsNumber(e.KeyChar) || e.KeyChar == '.')
{
if (Regex.IsMatch(
txtHraRep.Text,
"^\\d*\\.\\d{2}$")) e.Handled = true;
}
else e.Handled = e.KeyChar != (char)Keys.Back;
}
Changing to "^\d*\.\d{1}$")) e.Handled = true;
output
You can do this without regex by just checking where the decimal separator is in your text and then making sure that is 2 less than the length of the string (1 decimal place and 1 less for array length)
var decSeparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
var idx = txtBasic.Text.IndexOf(decSeparator);
if(idx + 2 >= txtBasic.Text.Length)
...
Instead of using a TextBox control for the input, look at using a MaskedTextbox control for your input. This will alleviate any self validation of the input and can show the users what input can be expected of them with messages as to why their input was not correct.
More information about the MaskedTextbox control:
MaskedTextbox
MaskedTextbox.Mask property
MSDN Walkthrough: Working with the MaskedTextBox Control
I just tried
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
{
if (char.IsNumber(e.KeyChar) || e.KeyChar == '.')
{
if (Regex.IsMatch(
textBox1.Text,
"^\\d*\\.\\d{1}$")) e.Handled = true;
}
else e.Handled = e.KeyChar != (char)Keys.Back;
}
}
and it worked as it should. It restricted the input to one digit after the decimal point.
But you could enter more than one decimal point and then also more digits.
So you can either try
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsNumber(e.KeyChar) || ((e.KeyChar == '.') && (textBox1.Text.IndexOf('.')== -1 )))
{
if (Regex.IsMatch(
textBox1.Text,
"^\\d*\\.\\d{1}$")) e.Handled = true;
}
else e.Handled = e.KeyChar != (char)Keys.Back;
}
or something like
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsNumber(e.KeyChar) || ((e.KeyChar == '.') && (textBox1.Text.IndexOf('.')== -1 )))
{
if (textBox1.Text.IndexOf('.') > 0)
{
if (textBox1.Text.IndexOf('.') < textBox1.Text.Length - 1)
e.Handled = true;
}
}
else e.Handled = e.KeyChar != (char)Keys.Back;
}
Create A new TextBox that inherit TextBox like
[DefaultBindingProperty("Text")]
[DefaultProperty("Text")]
[DefaultEvent("ValueChanged")]
public class SpecializedTextBox : TextBox
{
private bool _allowNegativeSign = false;
public bool AllowNegativeSign
{
get { return _allowNegativeSign; }
set { _allowNegativeSign = value; }
}
public decimal? DecimalValue
{
get
{
decimal k;
if (decimal.TryParse(this.Text, out k))
return k;
else
return null;
}
set
{
if (value.HasValue)
this.Text = value.Value.ToString();
else
this.Text = "";
}
}
private void This_TextChanged(object sender, EventArgs e)
{
string s = base.Text;
int cursorpos = base.SelectionStart;
bool separatorfound = false;
for (int i = 0; i < s.Length; )
{
if (char.IsNumber(s[i]))
i++;
else if (AllowNegativeSign && i < System.Globalization.CultureInfo.CurrentUICulture.NumberFormat.NegativeSign.Length && s.StartsWith(System.Globalization.CultureInfo.CurrentUICulture.NumberFormat.NegativeSign))
i++;
else if (!separatorfound && s[i].ToString() == System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator)
{
separatorfound = true;
i++;
}
else
{
s = s.Remove(i, 1);
if (i < cursorpos)
cursorpos--;
}
}
if (base.Text != s)
{
base.Text = s;
base.SelectionStart = cursorpos;
base.SelectionLength = 0;
}
if (ValueChanged != null)
ValueChanged(this, EventArgs.Empty);
}
public event EventHandler ValueChanged;
private void InitializeComponent()
{
this.SuspendLayout();
//
// SpecializedTextBox
//
this.TextChanged += new System.EventHandler(this.This_TextChanged);
this.ResumeLayout(false);
}
public SpecializedTextBox()
: base()
{
InitializeComponent();
}
}
now use this text box and use DecimalValue to set or get your value
try:
List<string> doubleList = new List<string>(new string[]
{
"12345",
"1234.5",
"123.45",
"12.345",
"1.2345",
"1.2",
"1.23",
"1.234",
"1.23.45",
"12.3",
"123.4",
}) { };
private void button1_Click(object sender, EventArgs e)
{
foreach (var x in doubleList)
{
int countNumber = Regex.Matches(x, #"[0-9]").Count;
int countOfDot = Regex.Matches(x, #"\.").Count;
if (countOfDot == 1 && countNumber != 0) //contains "." and any digit
{
Console.WriteLine(x);
}
else if (countOfDot == 0 && countNumber != 0) //not contains "." and any digit
{
Console.WriteLine(x);
}
else
{
//do nothing . . .
}
}
}
output:
all except for **1.23.45** (2dots)
I am using the following code in order to implement undo/redo into my application:
public struct UndoSection
{
public string Undo;
public int Index;
}
--
public UndoSection(int index, string undo)
{
Index = index;
Undo = undo;
}
--
Stack<UndoSection> UndoStack = new Stack<UndoSection>();
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Modifiers == Keys.None && e.KeyCode == Keys.Delete)
UndoStack.Push(new UndoSection(richTextBoxPrintCtrl1.SelectionStart, richTextBoxPrintCtrl1.SelectedText));
else if (e.Control && e.KeyCode == Keys.Z)
{
e.Handled = true;
undo_Click(richTextBoxPrintCtrl1, new EventArgs());
}
}
public string[] RTBRedoUndo;
public int StackCount = 0;
public int OldLength = 0;
public int ChangeToSave = 5;
public bool IsRedoUndo = false;
--
public void RTBTextChanged()
{
if (richTextBoxPrintCtrl1.TextLength - OldLength >= ChangeToSave | richTextBoxPrintCtrl1.TextLength - OldLength <= ChangeToSave)
{
StackCount += 1;
RTBRedoUndo[StackCount] = richTextBoxPrintCtrl1.Text;
}
}
public void UndoCode()
{
IsRedoUndo = true;
if (StackCount > 0 && RTBRedoUndo[StackCount - 1] != null)
{
StackCount = StackCount - 1;
richTextBoxPrintCtrl1.Text = RTBRedoUndo[StackCount];
}
}
public void RedoCode()
{
if (IsRedoUndo == false && richTextBoxPrintCtrl1.Text.Substring(richTextBoxPrintCtrl1.Text.Length - 1, 1) == " ")
IsRedoUndo = true;
if (StackCount > 0 && RTBRedoUndo[StackCount + 1] != null)
{
StackCount = StackCount + 1;
richTextBoxPrintCtrl1.Text = RTBRedoUndo[StackCount];
}
However, if I type some text in my rich text box such as: "Hello. This is my application.", It will only let me redo up to "my". It won't let me redo "application.". And if I undo all text, I then cannot redo and restore the text.
What is causing this to behave in this manner? I really need to get this undo/redo code working correct. Could somebody help point me in the right direction, please?
--EDIT--
Redo code:
public void RedoCode()
{
if (IsRedoUndo == false && richTextBoxPrintCtrl1.Text.Substring(richTextBoxPrintCtrl1.Text.Length - 1, 1) == " ")
IsRedoUndo = true;
if (StackCount > 0 && RTBRedoUndo[StackCount + 1] != null)
{
StackCount = StackCount + 1;
richTextBoxPrintCtrl1.Text = RTBRedoUndo[StackCount];
}
}
It is called by a button click, using RedoCode();
Can you show how to call the Redo function?
as from what I can see you've missed out the below code
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Modifiers == Keys.None && e.KeyCode == Keys.Delete)
UndoStack.Push(new UndoSection(richTextBoxPrintCtrl1.SelectionStart, richTextBoxPrintCtrl1.SelectedText));
else if (e.Control && e.KeyCode == Keys.Z)
{
e.Handled = true;
undo_Click(richTextBoxPrintCtrl1, new EventArgs());
}
else if (e.Control && e.KeyCode == Keys.Y)
{
e.Handled = true;
redo_Click(richTextBoxPrintCtrl1, new EventArgs());
}
I want a Decimal Point in an Integer. If decimal Point is not there it shows Error Message.
Sir, The following code is written in User Control Text Box.The maximum Length given by the user When he access the user control.
The following code is restricts the user to enter the Decimal point after the maximum length.
Please the run the code Sir,
public virtual int MaximumLength { get; set; }
private void txtCurrency_KeyPress(object sender, KeyPressEventArgs e)
{
txtCurrency.MaxLength = MaximumLength + 3;
int dotIndex = txtCurrency.Text.IndexOf('.');
if (e.KeyChar != (char)Keys.Back)
{
if (char.IsDigit(e.KeyChar))
{
if (dotIndex != -1 && dotIndex < txtCurrency.SelectionStart && txtCurrency.Text.Substring(dotIndex + 1).Length >= 2)
{
e.Handled = true;
}
else if (txtCurrency.Text.Length == MaximumLength)
{
if (e.KeyChar != '.')
{ e.Handled = true; }
}
}
else
{
e.Handled = e.KeyChar != '.' || dotIndex != -1 || txtCurrency.Text.Length == 0 || txtCurrency.SelectionStart + 2 < txtCurrency.Text.Length;
}
}`enter code here`
decimal myValue = 12.4m;
int value = 0;
if (myValue - Math.Round(myValue) != 0)
{
throw new Exception("Has a decimal point");
}
else
{
value = (int)myValue;
}
You can use the RegularExpressions
private void textBox2_Validating(object sender, CancelEventArgs e)
{
Regex r = new Regex(#"^\d+.\d{0,1}$");
if (r.IsMatch(textBox2.Text))
{
MessageBox.Show("Okay");
}
else
{
e.Cancel = true;
MessageBox.Show("Error");
}
}
UPDATE:
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
e.Handled = true;
if (e.KeyChar == '.'
&& (textBox2).Text.IndexOf('.') > -1) //Allow one decimal point
e.Handled = true;
}
On the text box, it should allow the user to enter only six decimal places. For example, 1.012345 or 1,012345.
If seven decimal places are tried, the entry should not be allowed.
Please refer to the below code.
private void textBox1_KeyDown_1(object sender, KeyEventArgs e)
{
bool numericKeys = (
( ((e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9) ||
(e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9)) &&
e.Modifiers != Keys.Shift) ||
e.KeyCode == Keys.OemMinus ||
e.KeyCode == Keys.OemPeriod ||
e.KeyCode == Keys.Decimal ||
e.KeyCode == Keys.Oemcomma
);
bool navigationKeys = (
e.KeyCode == Keys.Up ||
e.KeyCode == Keys.Right ||
e.KeyCode == Keys.Down ||
e.KeyCode == Keys.Left ||
e.KeyCode == Keys.Home ||
e.KeyCode == Keys.End ||
e.KeyCode == Keys.Tab);
bool editKeys = (e.KeyCode == Keys.Delete ||
e.KeyCode == Keys.Back);
TextBox aTextbox = (TextBox)sender;
aTextbox.Text = "2,33333";
if (!string.IsNullOrEmpty(aTextbox.Text))
{
double maxIntensity;
string aTextValue = aTextbox.Text;
bool value = double.TryParse(aTextValue,
NumberStyles.Any,
CultureInfo.InvariantCulture.NumberFormat,
out maxIntensity);
if (value)
{
string aText = maxIntensity.ToString();
MessageBox.Show("the value is {0}", aText);
string[] args = aText.Split('.');
if (numericKeys)
{
bool handleText = true;
if (args.Length > 2)
{
handleText = false;
}
else
{
if (args.Length == 2 && args[1] != null && args[1].Length > 5)
{
handleText = false;
}
}
if (!handleText)
{
e.SuppressKeyPress = true;
e.Handled = true;
}
}
}
}
if (!(numericKeys || editKeys || navigationKeys))
{
e.SuppressKeyPress = true;
e.Handled = true;
}
}
To achieve the culture neutrality, the text value is converted to double first and then
the double value is converted to string.
bool value = double.TryParse(aTextValue,
NumberStyles.Any,
CultureInfo.InvariantCulture.NumberFormat,
out maxIntensity);
if (value)
{
string aText = maxIntensity.ToString();
}
Splitting the strings to separate the real part and mantissa part (both are stored are strings), then I check the length of the mantissa part. If the length of the string is more than 5, I'd like to suppress the key.
Is there aother approach to do this?
I've had luck with code similar to the following:
public class RegexMaskedTextBox : TextBox
{
private Regex _regex = new Regex(string.Empty);
public string RegexPattern
{
get { return _regex.ToString(); }
set { _regex = new Regex(value); }
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
string sNewText = this.Text;
string sTextToInsert = e.KeyChar.ToString();
if (this.SelectionLength > 0)
{
sNewText = this.Text.Remove(this.SelectionStart, this.SelectionLength);
}
sNewText = sNewText.Insert(this.SelectionStart, sTextToInsert);
if (sNewText.Length > this.MaxLength)
{
sNewText = sNewText.Substring(0, this.MaxLength);
}
e.Handled = !_regex.IsMatch(sNewText);
base.OnKeyPress(e);
}
}
I think I would solve this by using regular expressions. On the key down event you can check the regex.
Maybe you want to check this out: Regular expression for decimal number
The textbox will only accept numbers and only one decimal point.
For example the textbox contains "12345.56". When the period is pressed a second time on the keyboard it must not appear in the textbox because the textbox already contains a period.
[0-9]+(\.[0-9][0-9]?)?
Go with regular expressions.
hande KeyPress event and assuming its windows
void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '.' )
{
if (richTextBox1.Text.Contains('.'))
e.Handled = true;
}
}
**//Only numeric with Two decimal place comes in textbox and if user want to enter decimal again or space it will not allowed.**
if ((e.Key >= Key.D0 && e.Key <= Key.D9 ||
e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9 || e.Key == Key.Decimal || e.Key == Key.OemPeriod))
{
string strkey = e.Key.ToString().Substring(e.Key.ToString().Length - 1, e.Key.ToString().Length - (e.Key.ToString().Length - 1));
if (e.Key >= Key.D0 && e.Key <= Key.D9 ||
e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9)
{
TextBox tb = sender as TextBox;
int cursorPosLeft = tb.SelectionStart;
int cursorPosRight = tb.SelectionStart + tb.SelectionLength;
string result1 = tb.Text.Substring(0, cursorPosLeft) + strkey + tb.Text.Substring(cursorPosRight);
string[] parts = result1.Split('.');
if (parts.Length > 1)
{
if (parts[1].Length > 2 || parts.Length > 2)
{
e.Handled = true;
}
}
}
if (((TextBox)sender).Text.Contains(".") && e.Key == Key.Decimal)
{
e.Handled = true;
}
}
else
{
e.Handled = true;
}
if (e.Key >= Key.A && e.Key <= Key.Z ||
e.Key == Key.Space)
{
e.Handled = true;
}
if (Keyboard.Modifiers == ModifierKeys.Shift && e.Key == Key.OemPeriod)
{
e.Handled = true;
}
private bool isValueEnteredExceed100(string textBoxValue, string inputText)
{
var countPeriod = textBoxValue.Count(x => x.ToString().Equals("."));
if (countPeriod <= 1)
{
bool isValidNumber = AreAllValidNumericChars(inputText);
if (isValidNumber == true || inputText == ".")
{
double enterdValue;
bool returnValue = false;
if (textBoxValue != string.Empty || textBoxValue != "")
{
enterdValue = Convert.ToDouble(textBoxValue);
if (enterdValue > 0 && enterdValue <= 100)
{
returnValue = true;
}
}
return returnValue;
}
else
{
return isValidNumber;
}
}
else
{
return false;
}
}
private void AcceptedFromTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
string textBoxValue = AcceptedFromTextBox.Text + e.Text;
if (textBoxValue == ".")
{
textBoxValue = "0" + e.Text;
AcceptedFromTextBox.Text = textBoxValue;
}
e.Handled = !isValueEnteredExceed100(textBoxValue, e.Text);
AcceptedFromTextBox.SelectionStart = AcceptedFromTextBox.Text.Length;
}
private bool AreAllValidNumericChars(string str)
{
Regex regex = new Regex(#"[0-9]$");
return regex.IsMatch(str);
}
Another example ,
private void txtPrice_KeyPress(object sender, KeyPressEventArgs e)
{
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;
}
}
Code on Keypress event of textbox
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;
}