While saving a collection with all the changes, how can i ensure that blank strings should go as NULLs? I am using linq, wpf, wcf.
I don't want to iterate for each record and each property of record to put a null if blank.
You can use a IValueConverter class like following :: Below code is for double, you can stimulate the behavior for other types
public class DoubleNullFromStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is double || value is double?) return value;
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
return null;
var strValue = value as string;
if (strValue == null || strValue.Trim().Length == 0)
return null; //allow empty strings and whitespaces
double doubleValue = 0;
if (double.TryParse(strValue, out doubleValue))
return doubleValue;
return value; //which will intenionally throw an error
}
}
Then Bind this to your control like following
<TextBox HorizontalAlignment="Left" Name="brokeragePaidText" VerticalAlignment="Top" Width="170" >
<TextBox.Text>
<Binding Source="{StaticResource insertTransaction}" Converter="{StaticResource DoubleNullFromStringConverter}" UpdateSourceTrigger="Explicit" Path="BrokeragePaid">
<Binding.ValidationRules>
<ExceptionValidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With