How to add a validation code for a custom Property
defined in a UserControl
. Consider the following piece of code:
public class Date
{
private int month = 7; // Backing store
public int Month
{
get
{
return month;
}
set
{
if ((value > 0) && (value < 13))
{
month = value;
}
}
}
}
It will check that Month
value be between 1 and 12, but I want to an Invalid input message be shown up too in case it's invalid. Any ideas ?
If value is not between 1 and 12 you can throw eg an InvalidOperationException
and handle it in your main thread.
public int Month
{
get
{
return month;
}
set
{
if ((value > 0) && (value < 13))
{
month = value;
}
else throw new InvalidOperationException("Invalid month");
}
}
Then something like...
private void textBox1_Validating(object sender, CancelEventArgs e)
{
try
{
date.Month = Convert.ToInt32(textbox1.Text);
}
catch(InvalidOperationException ex)
{
e.Cancel = true;
textBox1.Select(0, textBox1.Text.Length);
// some message about invalid value
}
}
where textBox1_Validating
is the validating event handler of the textbox.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.