C#帮助创建自定义控件
问题描述:
我试图制作一个自定义控件,它接受输入取决于所选的选项。我想限制小数点只有一个,所以用户不会输入多个“。”。我怎样才能做到这一点?C#帮助创建自定义控件
using System;
using System.Windows.Forms;
using System.ComponentModel;
namespace DT_Controls
{
public enum Options { Any, Alphabets, Alpha_Numeric, Numeric }
public class TextBox_Pro : TextBox
{
Options _Opt = 0;
bool _Flag = false;
int Count = 0;
[Category("Behavior")]
[Description("If set as true will accept decimal values when SetOption is Numeric")]
public bool AcceptDecimal
{
get { return _Flag; }
set { _Flag = value; }
}
[Category("Behavior")]
[Description("Controls the type of value being entered into the TextBox_Pro")]
public Options SetOption
{
get { return _Opt; }
set { _Opt = value; }
}
public TextBox_Pro()
{
this.KeyPress += TextBox_Pro_KeyPress;
}
private void TextBox_Pro_KeyPress(object sender, KeyPressEventArgs e)
{
if (Convert.ToInt32(e.KeyChar) == 8)
return;
switch (_Opt)
{
case Options.Numeric:
if (_Flag == true)
if (Convert.ToInt32(e.KeyChar) == 46)
return;
if (char.IsDigit(e.KeyChar) == false)
{
MessageBox.Show("Enter Numeric Values Only");
e.Handled = true;
}
break;
case Options.Alphabets:
if(char.IsLetter(e.KeyChar)==false && Convert.ToInt32(e.KeyChar) != 32)
{
MessageBox.Show("Enter Only Aplhabets");
e.Handled = true;
}
break;
case Options.Alpha_Numeric:
if (char.IsLetterOrDigit(e.KeyChar) == false)
{
MessageBox.Show("Enter Only Alphabets Or Numbers");
e.Handled = true;
}
break;
}
}
}
}
例如,我不想让用户输入12 ..... 123我希望用户输入12.123和之后。它应该禁用该标志,但是当我这样做,它不会让我允许输入任何“。”即使在删除“。”之后。
答
不是设置任何标志,更容易被检查,如果你的文本框已经包含任何“”具有内置功能。因此,将以下代码:
if (_Flag == true)
if (Convert.ToInt32(e.KeyChar) == 46)
return;
有:
if (Convert.ToInt32(e.KeyChar) == 46)
{
if (this.Text.Contains("."))
{
e.Handled = true;
}
return;
}
这种方式,你也可以检查其他的不一致,如检查,如果在文本框中的文本的开头有“”
答
不同文化使用不同数量的小数点分隔符,所以这是最好的阅读从CultureInfo.CurrentCulture.NumberFormat
,而不是硬编码的值。由于您从TextBox
继承,因此您可以覆盖OnKeyPress
而不是订阅KeyPress
事件。如果小数点分隔符是第一个字符,则以下示例也自动显示0.。
[ToolboxBitmap(typeof(TextBox))]
public class TextBoxPro
: TextBox
{
static NumberFormatInfo s_numberFormatInfo = CultureInfo.CurrentCulture.NumberFormat;
public static readonly string s_decimalSeparator = s_numberFormatInfo.NumberDecimalSeparator;
protected override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
if (ReadOnly)
return;
var keyChar = e.KeyChar;
var keyString = keyChar.ToString();
if (keyString == s_decimalSeparator)
{
if (IsAllSelected)
{
e.Handled = true;
Text = "0.";
SelectionStart = 2;
}
else if (Text.Contains(s_decimalSeparator))
e.Handled = true;
}
}
private bool IsAllSelected
{
get { return SelectionLength == TextLength; }
}
}
非常感谢你,那完全工作:)我需要那个标志,因为我需要一个属性被设置天气允许小数或不。 – DeadlyTitan