Jump to content
  • Advertisement
Sign in to follow this  
fafanne

[.net] CSharp Textbox Validation On Pasting Text In. Plz Post Answer!

This topic is 3663 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello Im using C-sharp vs2005. My problem is that Im putting some validations on a form. There is a textbox which I allow only numeric keys to be entered.I put a validation in the keypress event and it's working alright. But it's only when Im keying the character that it will validate the entries! If I have alphanumerics characters in the clipboard and paste in the textbox, my validations are violated! There are alphanumeric characters in my textbox where there should only numeric keys. Can somebody help me out there? What I would like to do is to validate the text before it goes in the textbox. How can I do this? Thanks in advance for your reply. Regards.

Share this post


Link to post
Share on other sites
Advertisement
You will need to handle both KeyPress and TextChanged events. That should cover both typing and pasting from the clipboard.

Share this post


Link to post
Share on other sites
Quote:
Original post by TheTroll
Do not do it on textchanged event, that can be very ugly.


What do you mean by ugly? I've used it before and it worked fine for me.

Share this post


Link to post
Share on other sites
Quote:
Original post by TheTroll
Do not do it on textchanged event, that can be very ugly.

Handle the OnPaste event.

theTroll


TheTroll, Im using C-Sharp Vs2005, there's no OnPaste Event, if there were, I would have used it. Where did you see that?

Share this post


Link to post
Share on other sites
Quote:
Original post by Headkaze
Quote:
Original post by TheTroll
Do not do it on textchanged event, that can be very ugly.


What do you mean by ugly? I've used it before and it worked fine for me.


Hi Headkaze, Can you please provide me a sample code on how you handle this perfectly?

Share this post


Link to post
Share on other sites
private string RemoveNonDigit(string str)
{
StringBuilder sb = new StringBuilder();

for (int i = 0; i < str.Length; i++)
{
if (Char.IsDigit(str))
sb.Append(str);
}

return sb.ToString();
}

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsLetterOrDigit(e.KeyChar))
{
if (!Char.IsDigit(e.KeyChar))
e.Handled = true;
}
}

private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox1.Text = RemoveNonDigit(textBox1.Text);
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!