将数据源的数据格式化显示,加上金额符号
例如,将textbox内的数值格式化加上货币符号,在textbox的内容改变时,textbox绑定的数据源的值的格式保持不变,还是数值,不会有货币符号。
创建一个Binding,向Parse事件和Format事件添加ConvertEventHandler委托,并通过DataBindings属性向TextBox控件的BindingsCollection添加Binding添加到 Format 事件的 DecimalToCurrencyString 事件委托使用 ToString 方法将绑定值(Decimal 类型)格式化为货币类型。 添加到 Parse 事件的 CurrencyStringToDecimal 事件委托将控件所显示的值转换回 Decimal 类型。
实现的代码如下:
private void MakeSet()
{
// Create a DataSet.
ds = new DataSet("myDataSet");
// Create DataTable.
DataTable tOrders = new DataTable("Orders");
// Create three columns, and add them to the table.
DataColumn cOrderAmount =
new DataColumn("OrderAmount", typeof(decimal));
tOrders.Columns.Add(cOrderAmount);
// Add the tables to the DataSet.
ds.Tables.Add(tOrders);
/* Populate the tables. For each customer and order,
create two DataRow variables. */
DataRow newRow1;
newRow1 = tOrders.NewRow();
newRow1["OrderAmount"] = Convert.ToDecimal(textBox2.Text.ToString());
tOrders.Rows.Add(newRow1);
}
protected void BindControls()
{
textBox1.DataBindings.Clear();
// Creates the binding first. The OrderAmount is a Decimal type.
Binding b = new Binding
("Text", ds, "Orders.OrderAmount");
// Add the delegates to the event.
b.Format += new ConvertEventHandler(DecimalToCurrencyString);
b.Parse += new ConvertEventHandler(CurrencyStringToDecimal);
textBox1.DataBindings.Add(b);
}
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);
}
参考链接:
# Binding.Parse 事件
http://msdn.microsoft.com/zh-cn/library/system.windows.forms.binding.parse.aspx