在行之间插入空格如果Gridview中的日期不同

时间:2015-04-20 12:32:56

标签: c# asp.net gridview asp.net-4.0 asp.net-4.5

我遇到了问题,我有一个gridview我想在行之间显示空格如果日期不同。

我试图添加新行但它有Id列和公司ID列不能为空。所以不能添加新的行。

现在我尝试在行之间添加空格。它适用于所有记录,但没有不同的日期条件。

我最终想要的是如果日期相同那么如果行数不同则行之间没有空格。

这将提供更好的可读性日期。

注意数据是按不同列排序的分组

我正在使用Mysql

2 个答案:

答案 0 :(得分:1)

假设您使用DataTable作为DataSource用于GridView(也以类似的方式使用不同的来源):

DataRow lastRow = null;
protected void GrdidView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataRow thisRow = ((DataRowView) e.Row.DataItem).Row;
        if(lastRow != null) // only add separators between two rows
        {
            DateTime thisDate = thisRow.Field<DateTime>("ColumnName");
            DateTime lastDate = lastRow.Field<DateTime>("ColumnName");
            if (thisDate.Date != lastDate.Date)
            {
                e.Row.Style.Add("border-top-width", "20px");
            }
        }
        lastRow = thisRow;
    }
}

答案 1 :(得分:0)

如果在GridView列中使用列模板,可以尝试这种方法。在GridView预渲染事件循环中通过表来比较日期。

<asp:GridView runat="server" id="GridView" AutoGenerateColumns="False" >
    <Columns>
            <asp:TemplateField>
               <ItemTemplate>
                <asp:Literal runat="server" id="ltDate" Text='<%#Bind("MyDate")%>' />
                </ItemTemplate>
            </asp:TemplateField>
    </Columns>
</asp:GridView>

private void GridView_PreRender(object sender, System.EventArgs e)
    {
    string sCompareDate = "";
    foreach (GridViewRow gvRow in GridView.Rows) {
        //First Row
        if (string.IsNullOrEmpty(sCompareDate))
            sCompareDate = ((Literal)gvRow.FindControl("ltDate")).Text;

        if (sCompareDate != ((Literal)gvRow.FindControl("ltDate")).Text) {
            gvRow.Cells(0).Attributes.Add("style", "border-bottom-width:30px;");
            sCompareDate = ((Literal)gvRow.FindControl("ltDate")).Text;
    }
}
}