C#中的Keypress事件 [英] Keypress event in C#
问题描述
我想在文本框中输入eky,它会在按键事件的标签上打印出来。
但是当我输入密钥时,它不会在标签上打印那个键那个时间。但是下次当我按下它显示标签中的文字。
例如当我在文本框中按2然后在标签中没有任何东西。
但是当我按23然后在标签2就在那里。
我尝试了什么:
private void txtdisount_KeyPress(object sender,KeyPressEventArgs e)
{
if(char.IsNumber(e.KeyChar)|| e .KeyChar =='。')
{
lblDisVal.Text = txtdisount.Text;
< br $>
}
其他
{
e.Handled = e.KeyChar!=(char)Keys.Back;
}
}
尝试这种
<预郎= C#> lblDisVal.Text = txtdisount.Text + e.KeyChar.ToString();
那是因为KeyPress事件发生在Text属性更新之前 - 如果没有,你将无法使用它阻止用户输入某些键!
使用TextChanged事件进行更新,使用Keypress进行过滤:
private void txtdisount_KeyPress( object sender,KeyPressEventArgs e)
{
if (!char.IsNumber(e.KeyChar)&& e.KeyChar!= ' 。')
{
e.Handled = e.KeyChar!=(炭跨度>)Keys.Back;
}
}
私有 void txtdisount_TextChanged( object sender,EventArgs e)
{
lblDisVal.Text = txtdisount.Text;
}但是......你可能会更好地使用NumericUpDown控件!
i want to enter eky in textbox which will print it in label on keypress event.
but when i am entering key it is not printing that key in label that time.but next time when i am pressing it shows that text in label.
for e.g when i press "2" in textbox then in label nothing is there.
but when i press "23" then in label "2" is there.
What I have tried:
private void txtdisount_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsNumber(e.KeyChar) || e.KeyChar == '.')
{
lblDisVal.Text = txtdisount.Text;
}
else
{
e.Handled = e.KeyChar != (char)Keys.Back;
}
}
try this
lblDisVal.Text = txtdisount.Text + e.KeyChar.ToString();
That's because the KeyPress event occurs before the Text property is updated - if it didn't you wouldn't be able to use it to prevent some keys being entered by the user!
Use the TextChanged event to update, and Keypress to filter:
private void txtdisount_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsNumber(e.KeyChar) && e.KeyChar != '.') { e.Handled = e.KeyChar != (char)Keys.Back; } } private void txtdisount_TextChanged(object sender, EventArgs e) { lblDisVal.Text = txtdisount.Text; }But...you'd probably be better off using a NumericUpDown control instead!
这篇关于C#中的Keypress事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!