如何在数据绑定在定制DataGridView的格式的数据 [英] How to custom format data in datagridview during databinding

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

问题描述

我正在寻找一种方式,使被databinded值绑定中被格式化格式化DataGridViewTextBoxColumn。比如我有一个公司名称属性,我需要在数据绑定情况采取前5个字母从公司名称。



我可以勾上不同的DataGridView事件(如RowsAdded)和环路通过所有的行和做的伎俩,但我想找到更复杂的方式来做到这一点。既然我已经决定使用数据绑定,通过数据的循环和修改是对数据绑定的概念了一下。



我是什么后,是怎么做的一样下面,但增加了自定义格式的逻辑:

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



我想我应该实现的IFormatProvider,但我不明白我应该怎么实现它。

  dataGridView1.Columns [companyName.Index] .DataPropertyName =公司名称; 
companyName.DefaultCellStyle.FormatProvider =新ShortText(); // ShortText应该实现的IFormatProvider


解决方案

我不知道有关的IFormatProvider,但可以在DataGridViews CellFormatting事件帮你吗?

 私人无效dataGridView1_CellFormatting(对象发件人,
DataGridViewCellFormattingEventArgs E)
{
如果(E 。.ColumnIndex == 0)
{
e.Value = e.Value.ToString()子串(0,5); //应用格式化这里
e.FormattingApplied = TRUE;
}
}

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


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.

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";

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

解决方案

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

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

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