首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

请问TextBox控制输入的有关问题

2012-02-27 
请教TextBox控制输入的问题在我的程序里面有这么一段:privatevoidperiod_tb_KeyPress(objectsender,KeyPre

请教TextBox控制输入的问题
在我的程序里面有这么一段:
private   void   period_tb_KeyPress(object   sender,   KeyPressEventArgs   e)
                {
                        e.Handled   =   (e.KeyChar   <   '0 '   ||   e.KeyChar   >   '9 '   ||   period_tb.Text.Length   >   1);
                        if   (e.KeyChar   ==   (Char)Keys.Back)
                        {
                                e.Handled   =   false;
                        }
                }
注:     period_tb为TextBox

用来控制最多只输入2位0-9的数字,   现在我的问题是,   当这个TextBox输入2位数字时,   我想双击这个TextBox来选中里面的Text(或者用鼠标将里面的Text全选),   然后就填上另外的数字,   但此时的TextBox已经被我控制不能再输入任何东西了(当然,   除了BackSpace),   大家有什么办法能让我在选中的情况下自由的输入其他数字呢?

[解决办法]
你可以用正則表達式來来控制0-9的数字,這個比你的效果一樣。双击这个TextBox来选中里面的Text(或者用鼠标将里面的Text全选), 然后就填上另外的数字,這個我也不曉得﹗抱歉﹗
private void txtSerialNo_TextChanged(object sender, EventArgs e)
{
string itemValue = txtSerialNo.Text.ToString();
if (IsNumeric(itemValue) == true)
{
ds.Tables[ "Dept "].Rows[bs.Position][ "SerialNo "] = int.Parse(txtSerialNo.Text.ToString().Trim());
}
else
{
txtSerialNo.Text = " ";
}
}

private static bool IsNumeric(string itemValue)
{
return (IsRegEx( "^(-?[0-9]*[.]*[0-9]{0,3})$ ", itemValue));
}

private static bool IsRegEx(string regExValue, string itemValue)
{

try
{
Regex regex = new System.Text.RegularExpressions.Regex(regExValue);
if (regex.IsMatch(itemValue)) return true;
else return false;
}
catch (Exception)
{
return false;
}
finally
{
}
}
[解决办法]
如下就可以了:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (this.textBox1.SelectionLength == 0)
{
e.Handled = (e.KeyChar < '0 ' || e.KeyChar > '9 ' || textBox1.Text.Length > 1);
if (e.KeyChar == (Char)Keys.Back)
{
e.Handled = false;
}
}
}

热点排行