2013-02-04 25 views
0

我有一个dataGridView,这是数据绑定到一些generic List<T>(而T是一些具有属性的自定义类)。 问题是,其中一个属性是integer类型,它代表了分钟。 将List绑定到dataGridView之后,我希望该列显示小时数,而不是默认分钟数。如何更改列值以显示绑定DataGridView中的不同值?

如何更改某些列的行为,使用它的一些数学来显示有点不同的值?

我必须在DataGridView.CellFormating事件中执行此操作吗?

回答

1

您有两种选择,第一种是首先操纵Generic List<T>,这应该比使用第二种选择更快,通过遍历每个RowDataBound Event上的列表。

  • 使用RowDataBound事件

    保护无效gridview1_RowDataBound(对象发件人,GridViewRowEventArgs E) { 如果(e.Row.RowType == DataControlRowType.DataRow) { INT分钟= INT。解析(e.Row.Cells [YourColumnIndex]。文本); 十进制小时=分钟/ 60;
    e.Row.Cells [YourColumnIndex] .Text = hours.ToString(); }}

  • 使用Evel表达

ASPX页面

<asp:TemplateField HeaderText="Time"> 
      <ItemTemplate> 
        <%# ConvertToHours(Eval("Minutes"))%> 
      </ItemTemplate> 
</asp:TemplateField> 

代码隐藏

private string ConvertToHours(object objMin) 
{ 
    if (Convert.ToInt32(objMin) == 1) 
    { 
     return (int.Parse(objMin)/60).ToString(); 
    } 
    else 
    { 
     return "0"; 
    } 
} 

另一种方法。 - 全力以赴。

<asp:TemplateField HeaderText="Time"> 
<ItemTemplate> 
<asp:Label ID="lblTime" runat="server" Text='<%# Convert.ToInt32(Eval("Time")) Convert.ToInt32("60")%>'></asp:Label> 
</ItemTemplate> 
</asp:TemplateField> 

更新:作为问题更新,那么对于Windows窗体应用程序,你应该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. 
     } 
    } 
} 
+0

我使用的是windows窗体使用。 –

+0

@MitjaBonca - ops!然后检查更新的答案。 – MuhammadHani

相关问题