Skip to content

Instantly share code, notes, and snippets.

@KentaYamada
Created April 28, 2014 00:28
Show Gist options
  • Save KentaYamada/11358920 to your computer and use it in GitHub Desktop.
Save KentaYamada/11358920 to your computer and use it in GitHub Desktop.
適当に作った数値入力テキスト
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace Usercontrols
{
[ToolboxBitmap(typeof(TextBox))]
public class NumberText : TextBox
{
public NumberText()
: base()
{
this.TextAlign = HorizontalAlignment.Right;
this.ImeMode = ImeMode.Disable;
this.KeyPress += new KeyPressEventHandler(this.NumberText_KeyPress);
this.TextChanged += new EventHandler(this.NumberText_TextChanged);
}
/// <summary>
/// 入力された数値を取得します。
/// </summary>
[Browsable(false)]
public decimal? Value
{
get
{
decimal? d = null;
if (!string.IsNullOrWhiteSpace(this.Text))
{
d = Convert.ToDecimal(this.Text.Replace(",", ""));
}
return d;
}
}
[Browsable(true)]
[Description("小数点付与の設定をします。")]
/// <summary>
/// 小数点付与の設定をします。
/// </summary>
public bool IsDecimalPoint { get; set; }
/// <summary>
/// 表示書式を設定します。
/// </summary>
[Browsable(true)]
[Category("表示")]
[Description("表示書式を設定します。")]
public string OutPutFormat { get; set; }
private void NumberText_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar < '0' || '9' < e.KeyChar) && e.KeyChar != '\b')
{
e.Handled = true;
return;
}
//e.Handled = Regex.IsMatch(e.KeyChar.ToString(), "^[0-9]+$") ? false : true;
}
private void NumberText_TextChanged(object sender, EventArgs e)
{
if (this.Name == this.Text) { return; }
double i = double.Parse(this.Text.Replace(",", ""));
this.Text = i.ToString(this.OutPutFormat);
this.Select(this.Text.Length, 0);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment