生活随笔
收集整理的這篇文章主要介紹了
自定义控件只允许输入Decimal和int类型字符串
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
為什么80%的碼農都做不了架構師?>>> ??
自定義控件中只放了一個TextBox控件,并在TextBox下利用自定義控件的Paint畫了一條線,然后給TextBox做了3個自定義屬性,分別是TextBoxText屬性,方便取值;IntBool屬性,是否只輸入正整數;inputDecimal是否只能輸入小數。
以下是整個自定義控件的源代碼
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;namespace GCIMS.CommonCtrl
{public partial class ctrlUnderlineTextBox : UserControl{#region 屬性/// <summary>/// 控件的文本/// </summary>[Description("文本值"), Browsable(true), Category("自定義屬性")]public string TextBoxText{get{return textBox.Text;}set{textBox.Text = value;}}private bool intBool;/// <summary>/// 只輸入正整數/// </summary>[Description("只輸入正整數"), Browsable(true), Category("自定義屬性"), DefaultValue(false)]public bool IntBool{get{return intBool;}set{intBool = value;if (intBool){textBox.KeyPress += new KeyPressEventHandler(IntBool_KeyPress);}}}private bool inputDecimal;/// <summary>/// 只輸入小數/// </summary>[Description("只輸入小數"), Browsable(true), Category("自定義屬性"), DefaultValue(false)]public bool InputDecimal{get{return inputDecimal;}set{inputDecimal = value;if (inputDecimal){textBox.KeyPress += new KeyPressEventHandler(InputDecimal_KeyPress);}}}#endregion#region 構造函數public ctrlUnderlineTextBox(){InitializeComponent();}#endregion#region 事件-ctrlUnderlineTextBox_KeyPressprivate void IntBool_KeyPress(object sender, KeyPressEventArgs e){if ((int)e.KeyChar >= 48 && (int)e.KeyChar <= 57 && textBox.Text.Length < 18 || (int)e.KeyChar == 8) //只能輸入0-9數字和BackSpace{e.Handled = false;}else{e.Handled = true;}}#endregion#region 事件-InputDecimal_KeyPressprivate void InputDecimal_KeyPress(object sender, KeyPressEventArgs e){//搜索字符串中的'.'字符string textBoxStr = textBox.Text;Regex rg = new Regex(".");MatchCollection mc = rg.Matches(textBoxStr);int textBoxCount = mc.Count;//允許輸入數字,小數點,退格鍵,不允許輸入大于18為的數字,不允許輸入兩個小數點if ((int)e.KeyChar >= 48 && (int)e.KeyChar <= 57 && textBox.Text.Length < 18 || (int)e.KeyChar == 8 || e.KeyChar == '.' && textBoxCount <= 1) //只能輸入0-9數字和BackSpace{e.Handled = false;}else{e.Handled = true;}}#endregion#region 事件-CtrlUnderlineTextBox_Paintprivate void CtrlUnderlineTextBox_Paint(object sender, PaintEventArgs e){Graphics g = Graphics.FromHwnd(this.Handle);System.Drawing.Pen pen = new Pen(Color.Black);PointF point1 = new PointF(textBox.Location.X, textBox.Location.Y + textBox.Height);PointF point2 = new PointF(textBox.Location.X + textBox.Width, textBox.Location.Y + textBox.Height);g.DrawLine(pen, point1, point2);}#endregion}
}
轉載于:https://my.oschina.net/dongri/blog/610931
總結
以上是生活随笔為你收集整理的自定义控件只允许输入Decimal和int类型字符串的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。