数据绑定时如何在datagridview中自定义格式数据 [英] How to custom format data in datagridview during databinding
问题描述
我正在寻找一种格式化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,但我不太明白我应该如何实现它。 / p>
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事件可以帮助你吗?
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屋!