set a nullable property in object

  • Thread starter Thread starter Rick
  • Start date Start date
R

Rick

I have a business object (class) with some nullable properties declared like
this:

Private _MyProp as Nullable(of Int16)
public Property MyProp as Nullable(Of Int16)
get
Return _MyProp
end get
set(ByVal Value as Nullable(Of Int16))
If not _MyProp.Equals(value) then
_MyProp = Value
NotifyPropertyChanged("MyProp") ' marks the property changed
end if
end set

I can read from my database with no problem for both MyProp's with or
without a value. When MyProp = 1 and I try to set it to Null in a Windows
TextBox, the form will not even let me move to another control. If I change
rows in a datagridview, the value is set back to 0.

So, I added an OnValidate event like this:

if String.IsNullOrEmpty(myControl.Text) then _
myBusinessObject.MyProperty = Nothing

Now I can set the nullable property to "Nothing" and it works as expected.
My question is - Is this the normal procedure to set a nullable value or am
I missing some shortcut where I don't have to add the OnValidate event?

Rick
 
Rick,

I would imagine that the code is attempting to set the Nullable value to ""
when there is nothing in the textbox, which is not null. I don't see any
harm in overriding the OnValidate event with the code you have, to perform
the translation from Empty to Null.

Hope this helps.

Steve
 
Rick schreef:
Now I can set the nullable property to "Nothing" and it works as expected.
My question is - Is this the normal procedure to set a nullable value or am
I missing some shortcut where I don't have to add the OnValidate event?

I prefer to do it at Parsing time...

this.myDataSource = new MyDataSource();
this.textBox1.DataBindings.Add("Text", this.myDataSource, "Double",
true);
this.textBox1.DataBindings["Text"].Parse += this.Text_Parse;

void Text_Parse( object sender, ConvertEventArgs e )
{
if( e.Value == null || e.Value.ToString().Length == 0 )
{
e.Value = null;
}
}
 
Back
Top