【问题标题】:How to avoid repetition of data in Gridview?如何避免 Gridview 中的数据重复?
【发布时间】:2011-11-29 11:44:02
【问题描述】:

在 Web 应用程序中,我将数据绑定到 GridView。在GridView 中,一些数据是重复的。我不想一次又一次地显示数据。

例如 Empid 在同一列中显示不止一次。我不想在该列中再次显示 empid。

【问题讨论】:

  • 在将数据发送到 gridview 之前,您确实应该进行此过滤/分组。此外,该网格的屏幕截图可能适合您的部分代码。

标签: asp.net data-binding gridview


【解决方案1】:

您可以为您正在使用的特定列实现OnDataBinding 事件。我从不使用AutoGenerateColumns,因此对每个单元进行精细控制非常容易实现。

例如:

// Create global in your .cs file
string _currentEmpID = string.Empty;

像这样定义你的列:

<Columns>
    <asp:TemplateField>
        <ItemTemplate>
            <asp:Literal ID="ltEmpID" runat="server" 
                OnDataBinding="ltEmpID_DataBinding" />
        </ItemTemplate>
    </asp:TemplateField>
    <!-- Your other columns... -->
</Columns>

然后执行您的DataBinding 事件:

protected void ltEmpID_DataBinding(object sender, System.EventArgs e)
{
    Literal lt = (Literal)(sender);
    string empID = Eval("EmpID").ToString();
    if (!empID.Equals(_currentEmpID))
    {
        lt.Text = empID;
        _currentEmpID = empID;
    }
    else
    {
        lt.Text = string.Empty;
    } 
}

RowDataBound 强制您搜索控件,如果将来需要更改,您可能会破坏事件中正在修改的其他内容。正因为如此,我更喜欢尽可能使用控件的 DataBinding 事件,因为它将功能仅本地化到控件,并让您可以灵活地轻松交换控件和功能,而不必担心影响其他事物。

【讨论】:

    【解决方案2】:

    如果在将数据绑定到数据源之前按不想重复的列对数据进行分组,则可以将事件绑定到 RowDataBound 并检查当前值是否等于前一个值,然后隐藏单元格。

    查看this 以获取示例。

    【讨论】:

      【解决方案3】:

      只需在 gridview 中添加属性 AutoGenerateColumns 并将其赋值为 false。

      AutoGenerateColumns="false"
      

      【讨论】:

        猜你喜欢
        • 2019-11-13
        • 2019-03-09
        • 2015-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-09
        相关资源
        最近更新 更多