【问题标题】:Insert Space Between rows If date Is Different in Gridview如果Gridview中的日期不同,则在行之间插入空格
【发布时间】:2015-04-20 12:32:56
【问题描述】:

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

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

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

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

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

注意数据按不同列排序

我正在使用 Mysql

【问题讨论】:

  • 你是如何绑定数据的?存储过程?如果您使用的是存储过程,那么您可以使用 tally table 创建一个日历并加入其中以获得不可用日期的空行。
  • 您可以使用此脚本在MySql - brianshowalter.com/calendar_tables 中创建calendar table
  • 网格的数据源是什么?
  • 不同于gridview中的其余日期?

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


【解决方案1】:

假设您将 DataTable 用作 GridView 的 DataSource(也以类似的方式与不同的源一起使用):

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;
    }
}

【讨论】:

  • 给出异常附加信息:指定的转换无效。我正在为数据库中的日期列使用日期时间
  • @Morfious:在哪里你得到异常了吗?如果您真的将其存储为DateTime,我怀疑它是否位于thisRow.Field&lt;DateTime&gt;("ColumnName")。如果你在调试器中查看e.Row.DataItem,它是什么类型的? DataSource 是指什么?
  • 嗨,蒂姆,我以这种方式使用你的代码对我来说效果很好。我对你的代码做了一些改动,现在我的项目中遇到了另一个问题。
  • 嗨,蒂姆,我以这种方式使用您的代码对我来说效果很好。我对您的代码做了一些更改,现在我的项目中出现了另一个问题。数据行 lastRow = null;由于行为空,此行正在停止我的 java 脚本运行。按钮单击事件上的java脚本通过复选框选择人员获得批准和不批准。因为Datarow lastRow = null;没有任何反应 java 脚本不适用于复选框选择的行
【解决方案2】:

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

<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;
    }
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 2021-07-24
    • 2018-08-07
    相关资源
    最近更新 更多