简体   繁体   English

在datagridview中格式化绑定数据

[英]Formatting bound data in datagridview

i have a DataGridView that is bound to a list of objects. 我有一个绑定到对象列表的DataGridView。 One of the the parameters of the objects is a price which is in cents and i would like to show in dollars, if i were to write it out directly i would do the following: 对象的参数之一是价格,单位为美分,我想以美元显示,如果我直接将其写出,我将执行以下操作:

row.Cells[5].Value = String.Format("€ {0:0.00}", oStockData.netPriceCents / 100);

i could go over the data afterwards but cannot commit the new formatted string to the bound object so only need the data displayed in another format. 我之后可以遍历数据,但是不能将新的格式化字符串提交给绑定的对象,因此只需要以另一种格式显示的数据即可。

As far as i can see it i have these options: 据我所见,我有以下选择:

  1. Save the actual base data in a non-browsable parameter and create another which can be changed to the required format and shown to the user. 将实际的基本数据保存在不可浏览的参数中,并创建另一个可以更改为所需格式并显示给用户的参数。

  2. Change the data when the datagridview is populated, then change it back to the original format when required. 填充datagridview后,请更改数据,然后在需要时将其更改回原始格式。

Is there are better way because the 2 above just seem dirty to me. 有没有更好的方法,因为上面的2对我来说似乎很肮脏。

I don't see any dirty in having "viewmodel" which represents data in the way user/UI need. 我没有看到“ viewmodel”以用户/ UI所需的方式表示数据的任何肮脏之处。

public class OrderLineViewModel
{
    private OrderLine _model;

    public OrderLineViewModel(OrderLine model)
    {
        _model = model;
    }

    public decimal Price
    {
        get
        {
            return _model.Price/100.0m;
        }
        set
        {
            _model.Price = value * 100.0m;
        }
    }
}

Then you can retrieve your data and "wrap" it with viewmodel class which will represent your data in UI way. 然后,您可以检索数据并将其与viewmodel类“包装”在一起,该类将以UI方式表示您的数据。

var data = GetOrderLines();
dataGridView.DataSource = data.Select(orderLine => new OrderLineViewModel(orderLine))
                              .ToList();

Format "€ 0.00" you can set in the datagridview's column settings. 可以在datagridview的列设置中设置“€0.00”格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM