如果所有行数据都为null隐藏列

时间:2013-07-03 11:50:51

标签: c# asp.net foreach telerik radgrid

使用MS Visual Studio 2012,Telerik,C#.ASP.NET。

我需要的逻辑如下:

If a columns data on all rows is null then hide the column

基本上,如果列有3行数据,如果全部为null,则不要显示该列,但是如果其中有1个值,则显示该列。

一直在玩:

foreach (GridColumn columns in dgvUserResults.Columns)
{
    if (columns != null)
    {
        columns.Visible = false;
    }
    else
    {
        columns.Visible = true;
    }
}

代码不起作用当然不会遍历foreach循环只是跳过它。尽管没有考虑到这一点,即使它确实迭代,我需要一种方法来检查所有列[name]行是否为空。有一个很好的Telerik一个班轮?

2 个答案:

答案 0 :(得分:4)

请尝试使用以下代码段。

使用UniqueName

protected void RadGrid1_PreRender(object sender, EventArgs e)
{
    foreach (GridColumn column in RadGrid1.MasterTableView.Columns)
    {
        // If you used ClientSelectColumn then below code is not worked For that you have to put condition
        //if(column.ColumnType  == "GridBoundColumn")

        int TotalNullRecords = (from item in RadGrid1.MasterTableView.Items.Cast<GridDataItem>()
                                where string.IsNullOrWhiteSpace(item[column.UniqueName].Text) ||
                                item[column.UniqueName].Text == "&nbsp;"
                                select item).ToList().Count;

        if (TotalNullRecords == RadGrid1.MasterTableView.Items.Count)
        {
            RadGrid1.MasterTableView.Columns.FindByUniqueName(column.UniqueName).Visible = false;
        }
    }
}

使用索引

protected void RadGrid1_PreRender(object sender, EventArgs e)
{


    foreach (GridColumn column in RadGrid1.MasterTableView.Columns)
    {
        // If you used ClientSelectColumn then below code is not worked For that you have to put condition
        //if(column.ColumnType  == "GridBoundColumn")

        int TotalNullRecords = (from item in RadGrid1.MasterTableView.Items.Cast<GridDataItem>()
                                where string.IsNullOrWhiteSpace(item[column.UniqueName].Text) ||
                                item[column.UniqueName].Text == "&nbsp;"
                                select item).ToList().Count;

        if (TotalNullRecords == RadGrid1.MasterTableView.Items.Count)
        {
            column.Visible = false;
        }


    }
}

答案 1 :(得分:0)

  For col = 0 To myRadGridView.ColumnCount
        Dim mustKeepColumn As Boolean = False
        For Each r In myRadGridView.Rows

            If Not String.IsNullOrEmpty(r.Cells(col).Value.ToString) Then
                mustKeepColumn = True
                Exit For
            End If

        Next
        If Not mustKeepColumn Then
            myRadGridView.Columns(col).IsVisible = False
        End If
    Next