1

我有 gridview,我想在数据绑定到 gridview 后隐藏一列,但出现以下错误。

“索引超出范围。必须为非负数且小于集合的大小。参数名称:索引”

我的 C# 代码如下,

 protected void grid_all_posts_DataBound(object sender, EventArgs e)
{
    if (grid_all_posts.Columns[1].Visible)
    {
        grid_all_posts.Columns[1].Visible = false;
    }
}

// Read all posts and fill  gridview
    //////////////////////////////////////////////////
    DbCommand dbCommand2;
    dbCommand2 = db.GetStoredProcCommand("SP_Select_News");
    db.AddInParameter(dbCommand2, "UserId", DbType.Guid, new Guid(Session["UserId"].ToString().Trim()));
    DataSet ds = db.ExecuteDataSet(dbCommand2);
    grid_all_posts.DataSource = ds;
    grid_all_posts.DataBind();
    //////////////////////////////////////////////////

我的 ASPX 代码,

<asp:gridview runat="server" ID="grid_all_posts" OnRowDataBound="grid_all_posts_DataBound"></asp:gridview>

你认为问题是什么?我如何隐藏第一列

4

2 回答 2

1

尝试像下面它会工作....

    DbCommand dbCommand2;
    dbCommand2 = db.GetStoredProcCommand("SP_Select_News");
    db.AddInParameter(dbCommand2, "UserId", DbType.Guid, new Guid(Session["UserId"].ToString().Trim()));
    DataSet ds = db.ExecuteDataSet(dbCommand2);
    grid_all_posts.DataSource = ds;
    grid_all_posts.DataBind();

**//after Databind Write the below code**

    if (grid_all_posts.Columns.Count > 0)
       grid_all_posts.Columns[0].Visible = false;
    else
    {
       grid_all_posts.HeaderRow.Cells[0].Visible = false;
       foreach (GridViewRow gvr in grid_all_posts.Rows)
       {
           gvr.Cells[0].Visible = false;
       }
     }
于 2013-02-11T16:12:22.223 回答
0

一种简单而通用的方法一直困扰着我很久 - 不需要任何类型的列计数,我今天终于找到了它;DataControlFieldCell.ContainingField.HeaderText

Private Sub GridView_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView.RowDataBound

    For Each r As GridViewRow In GridView.Rows

        If r.RowType = DataControlRowType.DataRow Then
            For Each c As DataControlFieldCell In r.Cells

                Dim h As String = c.ContainingField.HeaderText
                If h <> "ColumnName" Then c.ContainingField.Visible = False
                If IsNumeric(c.Text) Then c.Text = Format(CInt(c.Text), "#,##0")

            Next
        End If

    Next

End Sub

当我对字段中的值执行一些格式设置时,我循环遍历 DataControlFieldCells(如上图所示),但是如果您想进一步减少它,您可以遍历我想象的标题。

有关详细信息,请参阅msdn 。

于 2013-11-25T07:47:53.300 回答