如何在数据绑定期间自定义数据网格视图中的数据格式 [英] How to custom format data in datagridview during databinding

查看:19
本文介绍了如何在数据绑定期间自定义数据网格视图中的数据格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种格式化 DataGridViewTextBoxColumn 的方法,以便在数据绑定期间格式化要绑定的值.例如,我有一个 CompanyName 属性,当数据绑定发生时,我需要从 CompanyName 中获取前 5 个字母.

I'm looking for a way to format DataGridViewTextBoxColumn so that the value to be databinded is formatted during databinding. For example I have a CompanyName property and I need to take first 5 letters from the CompanyName when databinding happens.

我可以挂钩不同的 DataGridView 事件(例如 RowsAdded)并遍历所有行并执行此操作,但我想找到更复杂的方法来执行此操作.由于我已经决定使用数据绑定,循环遍历数据并修改它有点违反数据绑定概念.

I could hook on different DataGridView events (e.g. RowsAdded) and loop through all the rows and do the trick, but I'd like to find more sophisticated way to do this. Since I have decided to use databinding, looping through data and modifying it is a bit against the databinding concept.

我所追求的是如何执行与下面相同的操作,但添加自定义格式逻辑:

What I'm after, is how to do the same as below, but add custom formatting logic:

dataGridView1.Columns[colSomeDate.Index].DataPropertyName = "SomeDate";
colSomeDate.DefaultCellStyle.Format = "yyyy";

我想我应该实现 IFormatProvider,但我不太明白我应该如何实现它.

I think I should implement IFormatProvider, but I don't quite understand how I should implement it.

dataGridView1.Columns[companyName.Index].DataPropertyName = "CompanyName";
companyName.DefaultCellStyle.FormatProvider = new ShortText(); // ShortText should implement IFormatProvider

推荐答案

我不知道 IFormatProvider,但是 DataGridViews CellFormatting-event 可以帮助您吗?

I don't know about the IFormatProvider, but can the DataGridViews CellFormatting-event help you?

private void dataGridView1_CellFormatting(object sender,
    DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex == 0)
    {
        e.Value = e.Value.ToString().Substring(0, 5); // apply formating here
        e.FormattingApplied = true;
    }
}

http://msdn.microsoft.com/en-us/library/z1cc356h.aspx?ppud=4

这篇关于如何在数据绑定期间自定义数据网格视图中的数据格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆