C# Reading Textbox ignoring characters

妖精的绣舞 提交于 2019-12-20 05:53:44

问题


Hi everyone i have a key down event as follows

if (e.KeyCode == Keys.C && e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
{
    var amount = textBox1.Text;
    var total = label3.Text;
    decimal damount = Math.Round(Convert.ToDecimal(amount), 2);
    decimal dtotal = Convert.ToDecimal(total);
    var ntotal = dtotal - damount;
    var ndue = Math.Round(Convert.ToDecimal(ntotal), 2);
    var ntotal1 = Convert.ToString(ndue);
    if (ndue <= 0)
    {
        panel4.Show();
        label4.Text = ntotal1;
    }
    else
    {
        label3.Text = ntotal1;
    }
    textBox1.Text = "";
    textBox1.Focus();
}

this event works like i want it but here is my question how do i when reading the textbox1.text ignore character such as c or a , since the keydown requires c it messes with my decimal conversion any suggestions


回答1:


Add e.SuppressKeyPress = true; e.Handled = true; to your handler when you want to prevent the key press from going forward.

As an aside, your if statement is equivalent to if (e.KeyCode == Keys.Return), since it will never be equal to both C and Enter.




回答2:


A while back I wrote a short post about restricting user input into TextBoxes, which is available here (Restricting allowed characters in TextBox) but one thing that I realised that it didn't handle was users pasting text that contains those characters into the TextBox for that the following may be of use to you (Stopping someone from pasting into a TextBox). Both of the posts were written in VB.NET but the code is simple enough that you shouldn't have any issues moving the code over to C#.

Hope this helps :)



来源:https://stackoverflow.com/questions/16125470/c-sharp-reading-textbox-ignoring-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!