Reputation:
I am working on windows form based application.
I want to validate textbox values. User enter only Numeric values in the textbox , now i am able to validate keypressevent, but i want validate copied value should be numeric then only paste(Mouse right click paste or Ctrl+v) textbox.
Upvotes: 1
Views: 2012
Reputation: 1
You can use something like this.
private void txtOrgao_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)
{
//Valida copy and paste com caracteres especiais
e.SuppressKeyPress = !Util.validaCaracteresEspeciaisClipBoard(txtOrgao);
}
}
private void txtOrgao_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsLetterOrDigit(Convert.ToChar(e.KeyChar)) &&
!Char.IsControl(Convert.ToChar(e.KeyChar)) &&
!Char.IsWhiteSpace(Convert.ToChar(e.KeyChar)))
{
e.Handled = true;
}
}
Helper class util:
public class Util
{
/// <summary>
/// Valida caracteres especiais em textBox para suprimir o evento KeyPress
/// Caracteres Inválidos: Simbolos
/// </summary>
/// <param name="caixaTexto">objeto TextBox</param>
/// <returns></returns>
static public Boolean validaCaracteresEspeciaisClipBoard(TextBox caixaTexto)
{
//Valida copy and paste com caracteres especiais
String clip = String.Empty;
if (Clipboard.ContainsText())
{
clip = Clipboard.GetText().Substring(0, caixaTexto.MaxLength);
for (int tam = 0; tam < caixaTexto.MaxLength; tam++)
{
if (!Char.IsLetterOrDigit(clip[tam]) &&
!Char.IsControl(clip[tam]) &&
!Char.IsWhiteSpace(clip[tam]))
{
return false;
}
}
}
return true;
}
}
Upvotes: 0
Reputation: 5558
When the user puts focus on a textbox (assuming a value has been copied from somewhere), you could check the last value copied to the Clipboard and either disable/remove focus from the control depending on your validation criteria.
Example of using the Clipboard in C#: http://www.codeproject.com/KB/shell/clipboard01.aspx
Upvotes: 0
Reputation: 349
The answer will depend on the level of feedback you want. If you want to give user feedback, I'd recommend using the Validating event and an ErrorProvider.
Here's an example: http://www.java2s.com/Tutorial/CSharp/0460__GUI-Windows-Forms/ErrorProvidernumbermustbeinarange.htm
Otherwise, just bind to the KeyDown or TextChanged events, and strip out any input you didn't want to be there. Depending on your exact validation requirements, you might also find a MaskedTextBox useful: http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx
Upvotes: 1