[英]NumericUpDown control with DataBinding to null property value not working
I have a method that sets up a numeric up down to display the value of a property in an object. 我有一种方法可以将数字向上设置以显示对象中属性的值。 That property value could be
null
. 该属性值可以为
null
。 I want the numeric up down to display zero if that's the case. 如果是这种情况,我希望数字向下显示零。 This is the code I'm using:
这是我正在使用的代码:
private void NudNullBindingSetup(NumericUpDown nud, MyObject obj, string propertyName)
{
var b = new Binding("Value", obj, propertyName, true,
DataSourceUpdateMode.OnPropertyChanged)
{
NullValue = 0,
DataSourceNullValue = null
};
nud.DataBindings.Add(b);
}
If I put a value in the NumericUpDown, then call this binding with an object that has a null
for the property, the control is still displaying the original value. 如果我在NumericUpDown中放置一个值,然后使用对该属性具有
null
的对象调用此绑定,则控件仍将显示原始值。
BTW, this method works perfectly if the object actually has a value in the property. 顺便说一句,如果对象实际上在属性中具有值,则此方法将完美工作。
What have I missed? 我错过了什么?
Edit: I should note this is a null
and not DBNull.Value
in the object property. 编辑:我应该注意这是一个
null
而不是object属性中的DBNull.Value
。
EDIT 编辑
You can simply set: 您可以简单地设置:
NullValue = (decimal)0,
DataSourceNullValue = null
And it works as expected. 它按预期工作。
Original 原版的
You can use Format
event to solve the problem. 您可以使用
Format
事件解决问题。
The Format event is raised when data is pushed from the data source into the control.
将数据从数据源推入控件时,将引发Format事件。 You can handle the Format event to convert unformatted data from the data source into formatted data for display.
您可以处理Format事件,以将数据源中的未格式化数据转换为可显示的格式化数据。
For example, here is what I wrote and works as expected in the question: 例如,这是我写的内容,并且按预期工作:
private void NudNullBindingSetup(NumericUpDown nud, MyObject obj, string propertyName)
{
var b = new Binding("Value", obj, propertyName, true, DataSourceUpdateMode.OnPropertyChanged);
b.NullValue = 0; /*Only used in Format event*/
b.DataSourceNullValue = null; /*Only used in Format event*/
b.Format += (s, e) =>
{
var binding = (Binding)s;
var control = (NumericUpDown)binding.Control;
control.Value =
e.Value == binding.DataSourceNullValue ?
(int)binding.NullValue : ((int?)e.Value).Value;
};
nud.DataBindings.Add(b);
}
And here is MyObject
这是
MyObject
public class MyObject
{
public int? Value { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.