2016-09-26 11 views
2

我想问,当iam使用事件keydown与计算文本的长度,它不匹配。但当我按下输入或退格时,它变成9。 有没有办法让它从1开始计数,而不是0keydown事件不能得到确切长度

代码我使用

private void textEdit1_KeyDown(object sender, KeyEventArgs e) 
    { 
     if (this.textEdit1.Text.Length == 10) 
     { 
      textEdit2.Text = textEdit1.Text;     
      this.textEdit1.Text = ""; 

     } 
     label2.Text = textEdit1.Text.Length.ToString(); 
     label1.Text = textEdit2.Text.Length.ToString(); 
    } 

enter image description here

回答

5

你必须尝试相同的Key_Up事件。

private void textEdit1_KeyUp(object sender, KeyEventArgs e) 
{ 
    if (this.textEdit1.Text.Length == 10) 
    { 
     textEdit2.Text = textEdit1.Text;     
     this.textEdit1.Text = ""; 

    } 
    label2.Text = textEdit1.Text.Length.ToString(); 
    label1.Text = textEdit2.Text.Length.ToString(); 
} 

因为Key_Down将在执行按键时以及释放按键之前执行。

而在另一侧Key_Up将在您释放键盘上的键后执行,因此键入的字符将出现在文本框中,您将得到所需的结果。

+0

我没有使用其他事件的预览键向下..是不是一样?我尝试阅读互联网上的一些信息,但我不安静地得到它 – chopperfield

0

问题是,在更新Text-property之前引发了KeyDown事件。如果您在处理密钥后需要文本的长度,则需要订阅另一个事件,例如,框TextChanged。