将数据源的数据格式化显示,加上金额符号



将数据源的数据格式化显示,加上金额符号


例如,将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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值