I need to set the Format of a TimeSpan such that days are displayed only if nonzero.
Right now I'm using @"d' days, 'hh\\:mm"
, which will format a new TimeSpan(1,2,3,4,5)
as 1 days, 02:03
, but it will also format a new TimeSpan(0,2,3,4,5)
as 0 days, 02:03
, which is not what I want - I want only 02:03
in that case.
The problem is that the exact same format will be applied to all of the time spans, which is the difference between my question and display timespan nicely , so I can't use (pseudo)code like this:
if (hasDays) {
format = @"dd' days, 'hh\:mm";
} else {
format = @"hh\:mm";
}
I can't use that, the condition must somehow be encoded in the format string itself. Is it possible to achieve that?
Please note: I am not interested in solutions that do not involve using the exact same format string. If it's impossible then an answer stating so is sufficient.
Conditional formatting is not possible using a format string; but depending on the control which shows data, you can use some solutions to perform conditional formatting.
In Windows Forms, complex data-binding is supported by ListBox
, ComboBox
, DataGridView
and DataGrid
. In this post I'll show how you can perform conditional formatting for these controls in Windows Forms applications.
ListBox and ComboBox
Set FormattingEnabled
to true
and handle Format
event. Use e.Value
to get item value and set the formatted value.
DataGridView
Handle CellFormatting
event. You can use e.Value
to get cell value or set the formatted value.
DataGrid
You can create a custom DataGridColumnStyle
, based on DataGridTextBoxColumn
and override GetColumnValueAtRow
and return formatted value.
In all below examples, I use a method to format value:
string FormatValue(object value)
{
if (value is TimeSpan)
{
var time = (TimeSpan)value;
if (time.TotalDays < 1.0)
return time.ToString(@"hh\:mm");
else
return time.ToString(@"d' days, 'hh\:mm");
}
return string.Format("{0}", value);
}
ListBox and ComboBox
void listBox_Format(object sender, ListControlConvertEventArgs e)
{
e.Value = FormatValue(e.Value);
}
DataGridView
void dg_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
e.Value = FormatValue(e.Value);
}
DataGrid
//public class MyDataGridTextBoxColumn : DataGridTextBoxColumn
protected override object GetColumnValueAtRow(CurrencyManager source, int rowNum)
{
var value = base.GetColumnValueAtRow(source, rowNum);
return FormatValue(value);
}
You should use this column style for the column which you want to use this format.
I think you can do this only in an event like DataGridView.CellFormatting
. Here you can give your cell an individual format.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.