有关TextBox中输入字符控制的一种解决办法

来源:互联网 发布:中韩进出口贸易数据 编辑:程序博客网 时间:2024/06/05 02:28
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
我们知道,在C#中,TextBox控件对输入字符的控制有keypress、keyup、和keydown事件来使用,但大家也看到了,这几个事件对输入字符的控制都有一定的缺陷,如果,你使用中文输入法,那么很多原来你不希望输入的字符也可以输入进去。这几天做程序的时候,就碰到了这个问题,我的解决思路很简单,既然这三个事件不再起作用,那么我就使用了TextBox控件中时刻能发生的TextChanged事件,以期望在这个事件中作些东西,以达到控制字符的目的。废话就不多说了,我将控制输入字符为数字的代码粘贴出来,希望大家多指正,如果能对你有益的话,我就更happy了。


private System.Windows.Forms.TextBox TextBox1;
private string text;
public Form1()
{
text = TextBox1.Text;
}
private void TextBox1_TextChanged(object sender, System.EventArgs e)
{
int len = text.Length;
if(len < TextBox1.Text.Length)
{
int index = TextBox1.Text.IndexOf(text);
char c = (TextBox1.Text.Remove(index,text.Length))[0];
if(c.CompareTo('0') < 0||c.CompareTo('9') >0)
{
TextBox1.Text = text;
TextBox1.SelectionStart = text.Length;
}
}
text = TextBox1.Text;

}

<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击