How to custom format data in datagridview during databinding(数据绑定期间如何在datagridview中自定义格式数据)
问题描述
我正在寻找一种格式化 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中自定义格式数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:数据绑定期间如何在datagridview中自定义格式数据


基础教程推荐
- 将 XML 转换为通用列表 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30