【问题标题】:How to hide row in GridView if certain column is empty?如果某列为空,如何在 GridView 中隐藏行?
【发布时间】:2015-10-27 23:50:04
【问题描述】:

我有一个GridView,它显示有关工作的一些信息,GridView 中的一个选项是选择一个原因。如果未选择原因,那么我不想在GridView 中显示该行。如何检查原因列中是否有值,如果为空如何隐藏该行?

private GridView BuildDebriefGridView()
    {
        GridView gv = new GridView();
        gv.AutoGenerateColumns = false;
        //gv.RowDataBound +=
        gv.Columns.Add(new BoundField { HeaderText = "Job No", DataField = "JobNo" });
        gv.Columns.Add(new BoundField { HeaderText = "Qty Rcvd", DataField = "QtyRcvd" });
        gv.Columns.Add(new BoundField { HeaderText = "Reason", DataField = "Reason" });
        gv.Columns.Add(new BoundField { HeaderText = "Comment", DataField = "Comment" });
        gv.Attributes.Add("style", "width:100%");

        return gv;
    }

【问题讨论】:

  • 难道你不能改变你的查询来不获取没有值的行吗?这会简单得多。
  • 使用 Gridview_RowDataBound 事件 ...
  • 你真的应该避免像这样在你的代码中放置 HTML 属性。最好用 CSS 来做这件事。
  • @Shirish 我需要向 Gridview_RowDataBound 函数添加什么?我在我的问题中添加了代码
  • 检查行隐藏的逻辑,gridview 事件中没有其他内容......

标签: c# asp.net visual-studio gridview


【解决方案1】:
void gv_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            JobPieceSerialNo item = e.Row.DataItem as JobPieceSerialNo;
            if (item != null)
            {
                if (string.IsNullOrEmpty(item.Reason))
                {
                    e.Row.Visible = false;
                }
            }
        }
    }

【讨论】:

  • e.Row.Visible=false 为我工作.. 像魔术一样工作!谢谢。
【解决方案2】:

使用GridView_RowDataBound 事件可以实现这一点。

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (e.Row.Cells[ReasonCellNumber].Text == "Reason")
        {
            e.Row.Visible = false;
        }
    }
}

【讨论】:

  • 我收到错误DataBinding: 'BaseClasses.JobsClasses.Job' does not contain a property with the name 'Reason'.
  • 这个错误是不言自明的。它告诉你没有名为Reason的属性。请参阅我的更新答案。您可以相应地更改它。请注意,您需要为Reason 单元格输入正确的单元格编号,即1
【解决方案3】:

尝试关注;

private void gvTransportListResults_RowDataBound(Object sender, GridViewRowEventArgs e)
 {
    if (e.Row.Cells["Reason"].Text == "") 
        e.Row.Visible = false;
 }

或者如果它是一个复选框

private void gvTransportListResults_RowDataBound(Object sender,   GridViewRowEventArgs e)
 {
    if(((CheckBox)e.Row.FindControl("YourCheckboxID")).Checked == false) 
        e.Row.Visible = false;
 }

【讨论】:

  • 导致错误The best overloaded method match for 'System.Web.UI.WebControls.TableCellCollection.this[int]' has some invalid arguments Error 36 Argument 1: cannot convert from 'string' to 'int'
  • 确保将正确的 ID 传递给 FindControl 方法
猜你喜欢
  • 1970-01-01
  • 2014-12-16
  • 1970-01-01
  • 2016-03-31
  • 2015-04-05
  • 2011-06-24
  • 2014-06-30
  • 2011-03-28
  • 1970-01-01
相关资源
最近更新 更多