Reputation: 4546
I have a dataGridView
, which is data bound to some generic List<T>
(while T is some custom class with properties).
The problem is that one of the property is type of integer
, and it represents minutes.
After binding List to dataGridView, I want that column shows hours, instead of minutes by default.
How to change some column`s behaviour, to use some math over it to show a bit different values?
Do I have to do this in the DataGridView.CellFormating
event?
Upvotes: 0
Views: 2473
Reputation: 8664
You have two options, the first one is to manipulate your Generic List<T>
first, that should be faster than using the second option, iterating through your list on each RowDataBound Event
.
Using RowDataBound
Event
protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int minutes = int.Parse(e.Row.Cells[YourColumnIndex].Text);
decimal hours = minutes / 60;
e.Row.Cells[YourColumnIndex].Text = hours.ToString();
}
}
Using Evel
Expression
ASPX Page
<asp:TemplateField HeaderText="Time">
<ItemTemplate>
<%# ConvertToHours(Eval("Minutes"))%>
</ItemTemplate>
</asp:TemplateField>
Code Behind
private string ConvertToHours(object objMin)
{
if (Convert.ToInt32(objMin) == 1)
{
return (int.Parse(objMin) / 60).ToString();
}
else
{
return "0";
}
}
Another approach. - do-it-all in single shot.
<asp:TemplateField HeaderText="Time">
<ItemTemplate>
<asp:Label ID="lblTime" runat="server" Text='<%# Convert.ToInt32(Eval("Time")) Convert.ToInt32("60")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Update: As the Question updated, Then for Windows Forms application you should use DataGridView.CellFormatting Event
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
// If the column is the Time column, check the
// value.
if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Time")
{
if (e.Value != null)
{
//Your implementation.
}
}
}
Upvotes: 1