Last active
August 30, 2016 08:08
-
-
Save bezzad/4789311918eceaf7855d087d9d3450b0 to your computer and use it in GitHub Desktop.
C#.Net Numeric TextBox by thousand separator like: 123,456,789
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class NumericTextBox : TextBox | |
{ | |
private const char Delete = (char)8; | |
private const char Backspace = '\b'; | |
public bool IsNumeric { get; set; } = false; | |
public new string Text | |
{ | |
get { return IsNumeric ? base.Text?.Replace(",", "") : base.Text; } | |
set | |
{ | |
var val = IsNumeric ? value?.Replace(",", "") : value; | |
base.Text = IsNumeric ? double.Parse(string.IsNullOrEmpty(val) ? "0" : val).ToString("N0") : val; | |
if(IsNumeric) Select(base.Text.Length, 0); | |
} | |
} | |
/// <summary> | |
/// Check typing char for numeric or not | |
/// </summary> | |
/// <param name="e"></param> | |
protected override void OnKeyPress(KeyPressEventArgs e) | |
{ | |
if (IsNumeric && e.KeyChar != Delete && e.KeyChar != Backspace && !char.IsDigit(e.KeyChar) /*&& e.KeyChar != '.'*/) | |
{ | |
e.Handled = true; // Reject the input | |
} | |
} | |
/// <summary> | |
/// Set new value to Text property | |
/// </summary> | |
/// <param name="e"></param> | |
protected override void OnTextChanged(EventArgs e) | |
{ | |
Text = base.Text; | |
base.OnTextChanged(e); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment