这个东西不难,只是大家第一时间都会想到在sql语句中做文章,不过觉得不爽,
解决的办法就是使用
Binding.Format 事件
和
Binding.Parse 事件
不过说实话,在我看《ado.net 技术内幕》之前也不知道可以这样来解决。
下面的示例创建一个 Binding,向 Parse 事件和 Format 事件添加 ConvertEventHandler 委托,并通过 DataBindings 属性向 TextBox 控件的 BindingsCollection 添加 Binding。添加到 Format 事件的 DecimalToCurrencyString 事件委托使用 ToString 方法将绑定值(Decimal 类型)格式化为货币。添加到 Parse 事件的 CurrencyStringToDecimal 事件委托将控件所显示的值回转为 Decimal 类型。
private void DecimalToCurrencyString(object sender, ConvertEventArgs cevent)
{
// The method converts only to string type. Test this using the DesiredType.
if(cevent.DesiredType != typeof(string)) return;
// Use the ToString method to format the value as currency ("c").
cevent.Value = ((decimal) cevent.Value).ToString("c");
}
private void CurrencyStringToDecimal(object sender, ConvertEventArgs cevent)
{
// The method converts back to decimal type only.
if(cevent.DesiredType != typeof(decimal)) return;
// Converts the string back to decimal using the static Parse method.
cevent.Value = Decimal.Parse(cevent.Value.ToString(),
NumberStyles.Currency, null);
}
private void BindControl()
{
// Creates the binding first. The OrderAmount is typed as Decimal.
Binding b = new Binding
("Text", ds, "customers.custToOrders.OrderAmount");
// Add the delegates to the event.
b.Format += new ConvertEventHandler(DecimalToCurrencyString);
b.Parse += new ConvertEventHandler(CurrencyStringToDecimal);
text1.DataBindings.Add(b);
}