我制作了一个自定义文本框,它将(可为空的)十进制值显示为时间(2.5 = 2:30)。我添加了一个属性“十进制?十进制值”,我将数据源绑定到该属性。这一切都很好,除非我清除文本框以使值为空。
它说“System.String 类型的对象无法转换为 System.Nullable`1[System.Decimal]”。
我看到的是 base.OnValidating 使 e.Cancel = True。因此,在下方某处执行了导致此问题的检查。不过我不理解这种行为,因为当我绑定到属性 Text 时,我可以毫无问题地清除文本框,并且正在保存空值。
绑定代码:
this.txtUrenDoorberekenen.DataBindings.Add(new System.Windows.Forms.Binding("DecimalValue", this.bsAutokraanOrderRegel, "Uren", true));
自定义属性:
[Browsable(true), Bindable(true), Category("DSE"), DefaultValue(null), Description("De numerieke waarde")]
public decimal? DecimalValue
{
get { return this.GeefNumeriek(this.Text); }
set { this.Text = this.GeefTijd(value); }
}
this.GeefNumeriek 返回一个小数?(它将文本框的文本转换为可以为空的小数)。this.GeefTijd(value) 将可以为空的十进制转换为字符串格式。
private decimal? GeefNumeriek(string waarde)
{
decimal? result = null;
if (!String.IsNullOrEmpty(waarde)) {
try {
// voeg dubbele punt toe, indien deze ontbreekt
if (waarde.Length == 1 && waarde.IndexOf(":") < 0) { waarde = waarde + ":00"; }
if (waarde.Length == 2 && waarde.IndexOf(":") < 0) { waarde = waarde + ":00"; }
if (waarde.Length >= 3 && waarde.IndexOf(":") < 0) { waarde = waarde.Substring(0, waarde.Length - 2) + ":" + waarde.Substring(waarde.Length - 2); }
// Uren gedeelte
result = Convert.ToDecimal(waarde.Substring(0, waarde.IndexOf(":")));
// Minuten
int minuten = Convert.ToInt16(waarde.Substring(waarde.IndexOf(":") + 1));
// Minuten kan niet meer dan 60 zijn
if (minuten > 60) { throw new Exception(DSETextResource.GeefText("Validatie_Numeriek_Ongeldig")); }
result = result + ((decimal)minuten / (decimal)60);
}
catch {
}
}
return result;
}