c# - 如何使这个 C# 函数可重用?

标签 c# winforms datagridview

我正在使用本文中提供的在 datagridview 中格式化时间戳的代码:

Format TimeSpan in DataGridView column

...我在添加到 datagridview_Cellformatting 事件中的代码时遇到问题。

这是有问题的代码:

private void dataGridView_CellFormatting(object sender, 
                                       DataGridViewCellFormattingEventArgs e)
{
    var formatter = e.CellStyle.FormatProvider as ICustomFormatter;
    if (formatter != null)
    {
        e.Value = formatter.Format(e.CellStyle.Format, 
                                   e.Value, 
                                   e.CellStyle.FormatProvider);
        e.FormattingApplied = true;
    }
}

这很好用,但我的问题是,鉴于我在应用程序中执行的数据绑定(bind)的性质,我需要在十个不同的 datagridview 对象上调用此方法。

您会注意到此方法捕获事件目标,这意味着我当前在代码中使用此方法的十个单独副本。必须有一种方法可以将其合并为一个方法,我可以从 CellFormatting 事件上的任何 datagridview 调用该方法。

有人知道如何做到这一点吗?

最佳答案

使用扩展方法。

namespace Foo 
{
    public static class DataGridExtensions
    {
        public static void FormatViewCell(this DataGridViewCellFormattingEventArgs e)
        {
            var formatter = e.CellStyle.FormatProvider as ICustomFormatter;
            if (formatter != null)
            {
                e.Value = formatter.Format(e.CellStyle.Format, 
                                           e.Value, 
                                           e.CellStyle.FormatProvider);
                e.FormattingApplied = true;
            }
        }
    }
}

关于数据网格单元格格式

using Foo;

private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    e.FormatViewCell();
}

关于c# - 如何使这个 C# 函数可重用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27424127/

相关文章:

c# - 最小化的应用程序显示在任务栏上方

c# - 我该怎么做 float :right in Windows Form Application?

c# - BadImageFormatException 处理

c# - protobuf-net、版本控制和代理类型的最佳实践

c# - RejectChanges 特定实体

c# - 在 C# 中获取 datagridview 中每一行的时间跨度

c# - 如何在datagridview中显示序列号?

c# - 调用 InvalidateCell 时 DataGridView 不调用 Paint 方法

C# 将 DataGridView 保存到文本文件

c# - 如何分离大型 ASP.NET MVC3 App?