【问题标题】:How can I conditionally bind a gridview row inside the RowDataBound event?如何在 RowDataBound 事件中有条件地绑定 gridview 行?
【发布时间】:2011-12-02 07:41:16
【问题描述】:

我有一个 Gridview,用于显示客户付款数据。默认情况下,我使用一些仅在 RowDataBound 事件中容易获得的检查来更改包含过期客户的任何行的显示。我想添加选项以根据输入过滤掉数据以仅显示过期或未过期的行。最好的方法是什么?

我的想法是这样的:

protected void gvTenantList_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (null != e.Row.DataItem)
    {
        DataRowView rowView = (DataRowView)e.Row.DataItem;
        if (hsPastDueLeases.Contains((int)rowView["LeaseID"]))
        {
            e.Row.CssClass += " pinkbg";
            if (showCurrentOnly) //code to prevent showing this row
        }
        else if (showPastDueOnly) //code to prevent showing this row
    }
}

基本上,我需要知道//code to prevent showing this row 中的内容

【问题讨论】:

    标签: c# asp.net gridview rowdatabound


    【解决方案1】:

    为什么在绑定之前不做过滤?

    例如

    gvTenantList.DataSource = data.Where(a=> !hsPastDueLeases.Contains(a.LeaseID)); // Of course you have a datatable so this is not 100% as easy as this
    

    或者您可以使用

    将行设置为不可见
    e.Row.Visible = false;
    
    
    protected void gvTenantList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (null != e.Row.DataItem)
        {
            DataRowView rowView = (DataRowView)e.Row.DataItem;
            if (hsPastDueLeases.Contains((int)rowView["LeaseID"]))
            {
                e.Row.CssClass += " pinkbg";
                e.Row.Visible = !showCurrentOnly;
            }
            else if (showPastDueOnly){ //code to prevent showing this row
                e.Row.Visible = false;
            }
        }
    }
    

    或者,您可以添加一个名为“隐藏”的 CssClass,并且在 css 中有

    .hidden { display: none; }
    

    但在大多数情况下,我认为您应该只对您真正想要的数据进行数据绑定,并将这样的业务逻辑排除在绑定事件之外。

    【讨论】:

    • 我对这种类型的数据函数不是很熟悉,但乍一看,它确实可以工作,而且比我想象的要干净得多。我只是有一个条件来控制它使用哪个数据源分配,基于过滤器控件。我喜欢;会试一试的!
    • 为了公平起见,请使用中间的 - e.Row.Visible。第一个更好,但如果你不得不在很长一段时间内搞砸它,那么以后再做。最后一个不太理想,因为它仍在发送给客户。
    • 我得到一个运行时异常:[NotSupportedException: Method 'Boolean Contains(Int32)' has no supported translation to SQL.]
    • 是的,这就是我说的意思,我说的不是那么清楚。您可能必须将数据表或您拥有的任何内容转换为一组业务对象并对其进行过滤。或者,您可以创建自己的 DataView 并设置行过滤器属性 - 但这有点讨厌。做我认为的 e.Row.Visible = false 选项。
    猜你喜欢
    • 1970-01-01
    • 2018-08-13
    • 2014-08-30
    • 2011-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多