繁体   English   中英

如何更改列值以在绑定DataGridView中显示不同的值?

[英]How to change column values to show different value in bind DataGridView?

我有一个dataGridView ,它是绑定到某些generic List<T> (而T是一些具有属性的自定义类)。 问题在于该属性之一是integer类型,它表示分钟。 将List绑定到dataGridView之后,我希望该列显示小时,而不是默认情况下的分钟。

如何更改某些列的行为,对其使用一些数学运算以显示一些不同的值?

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

您有两个选择,第一个选择是第一个操作您的Generic List<T> ,它比第二个选择要快,它遍历每个RowDataBound Event列表。

  • 使用RowDataBound事件

    protected void gridview1_RowDataBound(object sender,GridViewRowEventArgs e){if(e.Row.RowType == DataControlRowType.DataRow){int分钟= int.Parse(e.Row.Cells [YourColumnIndex] .Text); 十进制小时=分钟/ 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.
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM