问题描述
我正在寻找一种格式化 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-我们/图书馆/z1cc356h.aspx?ppud=4
这篇关于数据绑定期间如何在datagridview中自定义格式数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!