Formatting TimeSpan in a DataGrid

H

Horselover Fat

Hi,

I have a column in a database that holds elapsed time in milliseconds
and I want to display that column in a DataGrid in a specific format
(d.hh:mm:ss.fff). However, the closest I can get is d.hh:mm:ss.ffffff.
Code snippets follow:

dt = new DataTable("Errors");
dt.Columns.Add("Occurred", typeof(TimeSpan));
// SELECT statement transforms milliseconds into ticks
string command = String.Format("SELECT (err.occurred*{0}) as Occurred
FROM errors err ORDER BY err.occurred",
TimeSpan.TicksPerMillisecond.ToString());
adapter = new SQLiteDataAdapter(command, this.TestDataView.Run.DBConn);
adapter.TableMappings.Add("Table", "Errors");
adapter.Fill(dt);

The column style is DataGridTextBoxColumn and I tried setting the
Format property to d.hh:mm:ss.fff but with no effect. I guess I've
misunderstood the fundamentals here. Presumably, the column in the
datagrid is just displaying the default ToString() representation of
TimeSpan. How do I make it use a format string to display the output I
want?

Any help greatly appreciated.
 
G

Galcho[MCSD.NET]

I had similar problem with DataTime type in GridView.
I suppose this is bug.

The workarround is: Create template fields and put value there with
<%# Eval("DateInserted", "{0:d}")%>
you can put yourown fomrating there

hope this helps
Galin Iliev[MCSD.NET]
www.galcho.com
 
H

Horselover Fat

Sounds a bit ASP.NET. I should have mentioned that I'm using Windows
Forms so I'm still stuck.
 
C

Claes Bergefall

Basically the DataGridTextBoxColumn works like this when it comes to
formating:

1. Check the datatype of the corresponding column (in your case TimeSpan)
2. Check if there is an overriden ToString method for that type that takes a
string parameter
3. If so, call that ToString method with the string provided in the Format
property
4. If not, call the standard ToString without parameters

Since TimeSpan only has a ToString method without parameters, setting the
Format property has no effect.

You might be able to use the Format and Parse event of the Binding class.
You can get the collection of Bindings by getting the BindingManagerBase (in
reality it's a CurrencyManager) from the BindingContext property of the
DataGrid . I haven't tried it so I don't know if it works or how hard it is.

/claes
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top