我有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>
您认为问题是什么?我如何隐藏第一列
答案 0 :(得分: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;
}
}
答案 1 :(得分: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。