在DataGridView列中格式化TimeSpan

在DataGridView列中格式化TimeSpan

本文介绍了在DataGridView列中格式化TimeSpan的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过 ,但都涉及CellStyle Format值中不可用的方法。我只想显示小时和分钟部分(16:05);不是秒(16:05:13)。我试图强制秒值为零,但仍然有一些像16:05:00。使用kludge如提供字符串或DateTime(并且仅显示小时/分钟部分)的缺点是有什么方法可以获得格式化来做我想要的。

解决方案

我刚才发现了这个。不幸的是,解决方案很有参与。好消息是它的工作原理。



首先,您需要一个 ICustomFormatter 实现,处理 TimeSpan 值。 .NET框架不包括这种类型的开箱即用;我猜猜这是因为微软不想处理格式化 TimeSpan 的歧义(例如,hh平均总时数还是只有小时分量?)以及随之而来的支持问题的冲击,当这些模糊性混淆了开发人员时。



没关系 - 只需实现自己的。以下是我写的一个示例类,它基本上使用(无论如何适用)*:

 类TimeSpanFormatter:IFormatProvider,ICustomFormatter 
{
private Regex _formatParser;

public TimeSpanFormatter()
{
_formatParser = new Regex(d {1,2} | h {1,2} | m {1,2} | s { 1,2} | f {1,7},RegexOptions.Compiled);


#region IFormatProvider成员

public object GetFormat(Type formatType)
{
if(typeof(ICustomFormatter).Equals( formatType))
{
return this;
}

返回null;
}

#endregion

#region ICustomFormatter成员

公共字符串格式(字符串格式,对象arg,IFormatProvider formatProvider)
{
if(arg is TimeSpan)
{
var timeSpan =(TimeSpan)arg;
return _formatParser.Replace(format,GetMatchEvaluator(timeSpan));
}
else
{
var formattable = arg as IFormattable;
if(formattable!= null)
{
return formattable.ToString(format,formatProvider);
}

return arg!= null? arg.ToString():string.Empty;
}
}

#endregion

私人MatchEvaluator GetMatchEvaluator(TimeSpan timeSpan)
{
return m => EvaluateMatch(m,timeSpan);
}

私人字符串EvaluateMatch(Match match,TimeSpan timeSpan)
{
switch(match.Value)
{
casedd :
return timeSpan.Days.ToString(00);
cased:
return timeSpan.Days.ToString(0);
casehh:
return timeSpan.Hours.ToString(00);
caseh:
return timeSpan.Hours.ToString(0);
casemm:
return timeSpan.Minutes.ToString(00);
casem:
return timeSpan.Minutes.ToString(0);
casess:
return timeSpan.Seconds.ToString(00);
cases:
return timeSpan.Seconds.ToString(0);
casefffffff:
return(timeSpan.Milliseconds * 10000).ToString(0000000);
caseffffff:
return(timeSpan.Milliseconds * 1000).ToString(000000);
casefffff:
return(timeSpan.Milliseconds * 100).ToString(00000);
caseffff:
return(timeSpan.Milliseconds * 10).ToString(0000);
casefff:
return(timeSpan.Milliseconds).ToString(000);
caseff:
return(timeSpan.Milliseconds / 10).ToString(00);
casef:
return(timeSpan.Milliseconds / 100).ToString(0);
default:
return match.Value;
}
}
}

我们还没有完成。使用此类型,您可以将自定义格式化程序分配给您要用于显示您的 TimeSpan DataGridView code>值。



让我们说这个列叫做Time;那么你会这样做:

  DataGridViewColumn timeColumn = dataGridView.Columns [Time]; 
timeColumn.DefaultCellStyle.FormatProvider = new TimeSpanFormatter();
timeColumn.DefaultCellStyle.Format =hh:mm;

所以现在你设置了,对吧?


$ b $那么,由于一些奇怪的原因,你还没有100%的方式。为什么自定义格式在这一点上不能踢,我真的不能告诉你。但是我们几乎完成了。最后一步是处理 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;
}
}

最后,我们完成了。设置要根据您的自定义规则格式化的 DataGridViewColumn DefaultCellStyle.Format 属性现在应该按预期工作。 / p>


I've seen these questions but both involve methods that aren't available in the CellStyle Format value. I only want to show the hours and minutes portion (16:05); not the seconds as well (16:05:13). I tried forcing the seconds value to zero but still got something like 16:05:00. Short of using a kludge like providing a string or a DateTime (and only showing the hour/minutes part) is there any way I can get the formatting to do what I want.

解决方案

I just discovered this myself. Unfortunately, the solution is pretty involved. The good news is that it works.

Firstly, you need an ICustomFormatter implementation that deals with TimeSpan values. The .NET framework does not include such a type out-of-the-box; I am guessing this is because Microsoft didn't want to have to deal with the ambiguity involved in formatting a TimeSpan (e.g., does "hh" mean total hours or only the hour component?) and the ensuing onslaught of support issues that would arise when these ambiguities confused developers.

That's OK -- just implement your own. Below is a sample class I wrote that uses basically the same custom format strings as DateTime (those that were applicable, anyway)*:

class TimeSpanFormatter : IFormatProvider, ICustomFormatter
{
    private Regex _formatParser;

    public TimeSpanFormatter()
    {
        _formatParser = new Regex("d{1,2}|h{1,2}|m{1,2}|s{1,2}|f{1,7}", RegexOptions.Compiled);
    }

    #region IFormatProvider Members

    public object GetFormat(Type formatType)
    {
        if (typeof(ICustomFormatter).Equals(formatType))
        {
            return this;
        }

        return null;
    }

    #endregion

    #region ICustomFormatter Members

    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        if (arg is TimeSpan)
        {
            var timeSpan = (TimeSpan)arg;
            return _formatParser.Replace(format, GetMatchEvaluator(timeSpan));
        }
        else
        {
            var formattable = arg as IFormattable;
            if (formattable != null)
            {
                return formattable.ToString(format, formatProvider);
            }

            return arg != null ? arg.ToString() : string.Empty;
        }
    }

    #endregion

    private MatchEvaluator GetMatchEvaluator(TimeSpan timeSpan)
    {
        return m => EvaluateMatch(m, timeSpan);
    }

    private string EvaluateMatch(Match match, TimeSpan timeSpan)
    {
        switch (match.Value)
        {
            case "dd":
                return timeSpan.Days.ToString("00");
            case "d":
                return timeSpan.Days.ToString("0");
            case "hh":
                return timeSpan.Hours.ToString("00");
            case "h":
                return timeSpan.Hours.ToString("0");
            case "mm":
                return timeSpan.Minutes.ToString("00");
            case "m":
                return timeSpan.Minutes.ToString("0");
            case "ss":
                return timeSpan.Seconds.ToString("00");
            case "s":
                return timeSpan.Seconds.ToString("0");
            case "fffffff":
                return (timeSpan.Milliseconds * 10000).ToString("0000000");
            case "ffffff":
                return (timeSpan.Milliseconds * 1000).ToString("000000");
            case "fffff":
                return (timeSpan.Milliseconds * 100).ToString("00000");
            case "ffff":
                return (timeSpan.Milliseconds * 10).ToString("0000");
            case "fff":
                return (timeSpan.Milliseconds).ToString("000");
            case "ff":
                return (timeSpan.Milliseconds / 10).ToString("00");
            case "f":
                return (timeSpan.Milliseconds / 100).ToString("0");
            default:
                return match.Value;
        }
    }
}

We're not finished yet. With this type in place, you are equipped to assign a custom formatter to the column in your DataGridView that you want to use for displaying your TimeSpan values.

Let's say that column is called "Time"; then you would do this:

DataGridViewColumn timeColumn = dataGridView.Columns["Time"];
timeColumn.DefaultCellStyle.FormatProvider = new TimeSpanFormatter();
timeColumn.DefaultCellStyle.Format = "hh:mm";

So now you're set up, right?

Well, for some odd reason, you're still not 100% of the way there. Why custom formatting can't kick in at this point, I honestly couldn't tell you. But we're almost done. The one final step is to handle the CellFormatting event to get this new functionality we've written to actually take effect:

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

At last, we're finished. Setting the DefaultCellStyle.Format property of the DataGridViewColumn you want formatted according to your custom rules should now work as expected.

这篇关于在DataGridView列中格式化TimeSpan的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-10 22:56