Reputation: 24666
Is there an easy way to show a formatted string representing a TimeSpan
field in a DataGridViewTextBoxColumn
of a DataGridView
?
I have an array of custom objects (returned by a web service) that I'm binding to my datagrid. These object have a TimeSpan
property. When I bind this property to the column of the datagrid I obtain the object name (something like MyApplication.MyClass.TimeSpan) and not the timespan string.
How can I solve?
NOTE:
At last I discovered my problem is that I get my array of objects from a web service.
It seems that TimeSpan
type cannot be xml-serialized, so the system class is re-classed into a custom object:
Upvotes: 2
Views: 2440
Reputation: 81429
Create a read-only string property in your object that will represent the formatted TimeSpan. Something like:
public class MyObject
{
private TimeSpan _myTimeSpan;
// ...
public string TimeSpanFormatted
{
get
{
return _myTimeSpan.ToString("c");
}
}
// ...
}
Then add a column for this property and hide the "raw" TimeSpan column.
See here for TimeSpan formatting info.
NOTE: For your column's properties be sure to set the DataMember to TimeSpanFormatted
Upvotes: 1
Reputation: 5150
This displayed a value for me:
class TimeSpanItem
{
public TimeSpan Time { get; set; }
}
and use this:
DataGridView dataGridView1 = new DataGridView();
DataGridViewTextBoxColumn Column1 = new DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)(dataGridView1)).BeginInit();
//
// dataGridView1
//
dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView1.Columns.AddRange(new DataGridViewColumn[] {
Column1});
dataGridView1.Location = new Point(38, 58);
dataGridView1.Name = "dataGridView1";
dataGridView1.Size = new Size(240, 150);
dataGridView1.TabIndex = 0;
//
// Column1
//
Column1.HeaderText = "Column1";
Column1.Name = "Column1";
Column1.DataPropertyName = "Time";
this.Controls.Add(dataGridView1);
((System.ComponentModel.ISupportInitialize)(dataGridView1)).EndInit();
List<TimeSpanItem> list = new List<TimeSpanItem>();
list.Add(new TimeSpanItem() { Time = DateTime.Now.TimeOfDay });
dataGridView1.DataSource = list;
Upvotes: 1