2013-03-26 34 views
0

我需要处理我的文本框的按键事件,以便用户在文本框中只输入数字数据,我有我的代码工作正常,即时贴在下面,但我担心的是,我有超过30个文本框与相同的要求,我不想为30个文本框的按键事件编写相同的代码,但我不能在一个方法中写这个代码,并调用该方法..有什么办法可以解决这个问题,这样我就可以wrilte代码在一个地方,并调用它在人的文本框或这让我的代码看起来标准的任何其它方式的按键事件,降低了线,即时通讯张贴下面在其他地方声明文本框按键事件代码并调用它?

 if (!char.IsControl(e.KeyChar) 
     && !char.IsDigit(e.KeyChar) 
     && e.KeyChar != '.') 
     { 
      e.Handled = true; 
     } 

     // only allow one decimal point 
     if (e.KeyChar == '.' 
      && (sender as TextBox).Text.IndexOf('.') > -1) 
     { 
      e.Handled = true; 
     } 

回答

1

当然我的代码,你可以使用所有文本框的一个事件处理程序

TextBox tb = new TextBox(); 
tb.KeyPress += tb_KeyPress; 

TextBox tb2 = new TextBox(); 
tb2.KeyPress += tb_KeyPress; 

    void tb_KeyPress(object sender, KeyPressEventArgs e) 
    { 
     if (!char.IsControl(e.KeyChar) 
    && !char.IsDigit(e.KeyChar) 
    && e.KeyChar != '.') 
    { 
     e.Handled = true; 
    } 

    // only allow one decimal point 
    if (e.KeyChar == '.' 
     && (sender as TextBox).Text.IndexOf('.') > -1) 
    { 
     e.Handled = true; 
    } 
    } 
+0

对不起,但我应该在哪里写这段代码TextBox tb = new TextBox(); tb.KeyPress + = tb_KeyPress; ....? – adityaa 2013-03-26 09:37:05

+0

@你在哪里创建你的文本框? – VladL 2013-03-26 09:38:13

+0

直接拖放..winforms – adityaa 2013-03-26 09:41:23

相关问题