GridView按代码隐藏列

我想在我的GridView中隐藏ID列,我知道代码

GridView1.Columns[0].Visible = false; 

但令人惊讶的是,我的GridView列的计数属性是0! 而我可以在GridView看到数据,所以有什么想法?

谢谢,

更新:

这里是填充GridView的方法的完整代码

 public DataSet GetAllPatients() { SqlConnection connection = new SqlConnection(this.ConnectionString); String sql = "SELECT [ID],[Name],[Age],[Phone],[MedicalHistory],[Medication],[Diagnoses] FROM [dbo].[AwadyClinc_PatientTbl]order by ID desc"; SqlCommand command = new SqlCommand(sql, connection); SqlDataAdapter da = new SqlDataAdapter(command); DataSet ds = new DataSet(); da.Fill(ds); return ds; } 

当您的GridView将其AutoGenerateColumns属性设置为true (默认值为true )时, GridView.Columns.Count将始终为0。

您可以显式声明您的列并将AutoGenerateColumns属性设置为false ,也可以在代码隐藏中使用它:

GridView.Rows[0].Cells.Count

一旦你的GridView数据被绑定,获得列计数,或者:

 protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e) { e.Row.Cells[index].Visible = false; } 

使用GridView的RowDataBound事件来设置一个不可见的列。

这对我有帮助

 this.myGridview.Columns[0].Visible = false; 

这里0是我想要隐藏的列索引。

您可以通过查询datacontrolfield集合以获取所需的列标题文本并将其可见性设置为true来隐藏特定列。

 ((DataControlField)gridView.Columns .Cast<DataControlField>() .Where(fld => (fld.HeaderText == "Title")) .SingleOrDefault()).Visible = false; 

我见过的一些答案解释了如何使单元格的内容不可见,而不是如何隐藏整个列,这正是我想要做的。

如果你有AutoGenerateColumns = "false" ,并且实际上使用了BoundField作为你想要隐藏的列,那么Bala的回答是光滑的。 但是,如果您使用TemplateField作为列,则可以处理DataBound事件并执行如下操作:

 protected void gridView_DataBound(object sender, EventArgs e) { const int countriesColumnIndex = 4; if (someCondition == true) { // Hide the Countries column this.gridView.Columns[countriesColumnIndex].Visible = false; } } 

这可能不是OP正在寻找的东西,但是当我发现自己提出同样的问题时,这就是我正在寻找的解决scheme。

如果你想在网格填充的时候隐藏这个列,你可以在aspx页面中这样做

 <asp:BoundField DataField="test" HeaderText="test" Visible="False" /> 

在这里,我绑定了像这样的数据集的gridview –

 GVAnswer.DataSource = DS.Tables[0]; GVAnswer.DataBind(); 

然后

然后我们在for循环中计算这样的行数

 for (int i = 0; i < GVAnswer.Rows.Count; i++) { } 

然后,我们find头后,我们希望使可见虚假

 GVAnswer.HeaderRow.Cells[2].Visible = false; 

那么在我们将该特定单元格的可见性视为虚假之后。

完整的代码是这样的



public void FillGVAnswer(int QuestionID) { try { OBJClsQuestionAnswer = new ClsQuestionAnswer(); DS = new DataSet(); DS = OBJClsQuestionAnswer.GetAnswers(QuestionID); GVAnswer.DataSource = DS.Tables[0]; GVAnswer.DataBind(); if (DS.Tables[0].Rows.Count > 0) { for (int i = 0; i < GVAnswer.Rows.Count; i++) { GVAnswer.HeaderRow.Cells[2].Visible = false; GVAnswer.HeaderRow.Cells[3].Visible = false; GVAnswer.HeaderRow.Cells[6].Visible = false; GVAnswer.HeaderRow.Cells[8].Visible = false; GVAnswer.HeaderRow.Cells[10].Visible = false; GVAnswer.HeaderRow.Cells[11].Visible = false; //GVAnswer.Rows[i].Cells[1].Visible = false; if (GVAnswer.Rows[i].Cells[4].Text == "T") { GVAnswer.Rows[i].Cells[4].Text = "Text"; } else { GVAnswer.Rows[i].Cells[4].Text = "Image"; } if (GVAnswer.Rows[i].Cells[5].Text == "View Image") { HtmlAnchor a = new HtmlAnchor(); a.HRef = "~/ImageHandler.aspx?ACT=AIMG&AID=" + GVAnswer.Rows[i].Cells[2].Text; a.Attributes.Add("rel", "lightbox"); a.InnerText = GVAnswer.Rows[i].Cells[5].Text; GVAnswer.Rows[i].Cells[5].Controls.Add(a); } if (GVAnswer.Rows[i].Cells[7].Text == "Yes") { j++; ViewState["CheckHasMulAns"] = j;// To Chek How Many answer Of a particulaer Question Is Right } GVAnswer.Rows[i].Cells[8].Visible = false; GVAnswer.Rows[i].Cells[3].Visible = false; GVAnswer.Rows[i].Cells[10].Visible = false; GVAnswer.Rows[i].Cells[6].Visible = false; GVAnswer.Rows[i].Cells[11].Visible = false; GVAnswer.Rows[i].Cells[2].Visible = false; } } } catch (Exception ex) { string err = ex.Message; if (ex.InnerException != null) { err = err + " :: Inner Exception :- " + ex.InnerException.Message; } string addInfo = "Error in getting Answers :: -> "; ClsExceptionPublisher objPub = new ClsExceptionPublisher(); objPub.Publish(err, addInfo); } }

如果你想隐藏一个名字而不是在GridView中的索引。 创buildDataTable或Dataset后,必须按名称find列的索引,然后将索引保存在像ViewStae,Session等全局variables中,然后在RowDataBound中调用它,如下例所示:

 string headerName = "Id"; DataTable dt = .... ; for (int i=0;i<dt.Columns.Count;i++) { if (dt.Columns[i].ColumnName == headerName) { ViewState["CellIndex"] = i; } } ... GridView_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Footer) { int index = Convert.ToInt32(ViewState["CellIndex"]); e.Row.Cells[index].Visible = false; } } 
  private void Registration_Load(object sender, EventArgs e) { //hiding data grid view coloumn datagridview1.AutoGenerateColumns = true; datagridview1.DataSource =dataSet; datagridview1.DataMember = "users"; // users is table name datagridview1.Columns[0].Visible = false;//hiding 1st coloumn coloumn datagridview1.Columns[2].Visible = false; hiding 2nd coloumn datagridview1.Columns[3].Visible = false; hiding 3rd coloumn //end of hiding datagrid view coloumns } } 

这里大多数的答案都没有解释 – 如果你需要使列再次可见和不可见,所有基于数据dynamic? 毕竟,不应该GridViews数据为中心?

如果要根据数据打开或closures列,该怎么办?

我的Gridview

 <asp:GridView ID="gvLocationBoard" runat="server" AllowPaging="True" AllowSorting="True" ShowFooter="false" ShowHeader="true" Visible="true" AutoGenerateColumns="false" CellPadding="4" ForeColor="#333333" GridLines="None" DataSourceID="sdsLocationBoard" OnDataBound="gvLocationBoard_DataBound" OnRowDataBound="gvLocationBoard_RowDataBound" PageSize="15" OnPreRender="gvLocationBoard_PreRender"> <RowStyle BackColor="#F7F6F3" ForeColor="#333333" /> <Columns> <asp:TemplateField HeaderText="StudentID" SortExpression="StudentID" Visible="False"> <ItemTemplate> <asp:Label ID="Label2" runat="server" Text='<%# Eval("StudentID") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Student" SortExpression="StudentName"> <ItemTemplate> <asp:Label ID="Label3" runat="server" Text='<%# Eval("StudentName") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Status" SortExpression="CheckStatusName" ItemStyle-HorizontalAlign="Center"> <ItemTemplate> <asp:HiddenField ID="hfStatusID" runat="server" Value='<%# Eval("CheckStatusID") %>' /> <asp:Label ID="Label4" runat="server" Text='<%# Eval("CheckStatusName") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="RollCallPeriod0" Visible="False"> <ItemTemplate> <asp:CheckBox ID="cbRollCallPeriod0" runat="server" /> <asp:HiddenField ID="hfRollCallPeriod0" runat="server" Value='<%# Eval("RollCallPeriod") %>' /> </ItemTemplate> <HeaderStyle Font-Size="Small" /> <ItemStyle HorizontalAlign="Center" /> </asp:TemplateField> <asp:TemplateField HeaderText="RollCallPeriod1" Visible="False"> <ItemTemplate> <asp:CheckBox ID="cbRollCallPeriod1" runat="server" /> <asp:HiddenField ID="hfRollCallPeriod1" runat="server" Value='<%# Eval("RollCallPeriod") %>' /> </ItemTemplate> <HeaderStyle Font-Size="Small" /> <ItemStyle HorizontalAlign="Center" /> </asp:TemplateField> .. etc.. 

请注意“RollCallPeriodn”,其中“n”是一个序列号。

我这样做的方式是devise隐藏所有列 ,我知道以后会打开(可见=“真”)或closures(可见=“假”),根据我的数据。

在我的情况下,我想要显示时间段到某一列。 例如,如果今天是早上九点,那么我想要显示早上六点,七点,八点和九点, 而不是上午十点,十一点,等等。

在其他的日子,我想显示所有的时间。 等等。

那么我们该怎么做呢?

为什么不使用PreRender来“重置” Gridview

 protected void gvLocationBoard_PreRender(object sender, EventArgs e) { GridView gv = (GridView)sender; int wsPos = 3; for (int wsCol = 0; wsCol < 19; wsCol++) { gv.Columns[wsCol + wsPos].HeaderText = "RollCallPeriod" + wsCol.ToString("{0,00}"); gv.Columns[wsCol + wsPos].Visible = false; } } 

现在打开你需要的列,根据findHeaderText的开始, 如果标题文本不是默认的 ,使列可见

  protected void gvLocationBoard_DataBound(object sender, EventArgs e) { //Show the headers for the Period Times directly from sdsRollCallPeriods DataSourceSelectArguments dss = new DataSourceSelectArguments(); DataView dv = sdsRollCallPeriods.Select(dss) as DataView; DataTable dt = dv.ToTable() as DataTable; if (dt != null) { int wsPos = 0; int wsCol = 3; //start of PeriodTimes column in gvLocationBoard foreach (DataRow dr in dt.Rows) { gvLocationBoard.Columns[wsCol + wsPos].HeaderText = dr.ItemArray[1].ToString(); gvLocationBoard.Columns[wsCol + wsPos].Visible = !gvLocationBoard.Columns[wsCol + wsPos].HeaderText.StartsWith("RollCallPeriod"); wsPos += 1; } } } 

我不会在这里透露SqlDataSource ,但是可以用PreRender ,我可以重置我的GridView并打开我想要的标题列。

所以它的工作方式是每次select不同的date或时间段作为标题显示时,它会在重新构buildgridview之前将GridView重置为默认标题文本和Visible =“false”状态。 否则,如果没有PreRender ,GridView将会拥有之前的数据标题,因为后面的代码会清除默认设置。

当列Id是未知的,而AutoGenerateColumns == true的时候,这是我工作的代码;

 <%@ Page Language="C#" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Drawing" %> <html> <head runat="server"> <script runat="server"> protected void Page_Load(object sender, EventArgs eventArgs) { DataTable data = new DataTable(); data.Columns.Add("Id", typeof(int)); data.Columns.Add("Notes", typeof(string)); data.Columns.Add("RequestedDate", typeof(DateTime)); for (int idx = 0; idx < 5; idx++) { DataRow row = data.NewRow(); row["Id"] = idx; row["Notes"] = string.Format("Note {0}", idx); row["RequestedDate"] = DateTime.Now.Subtract(new TimeSpan(idx, 0, 0, 0, 0)); data.Rows.Add(row); } listData.DataSource = data; listData.DataBind(); } private void GridView_RowDataBound(object sender, GridViewRowEventArgs e) { foreach (TableCell tableCell in e.Row.Cells) { DataControlFieldCell cell = (DataControlFieldCell)tableCell; if (cell.ContainingField.HeaderText == "Id") { cell.Visible = false; continue; } if (cell.ContainingField.HeaderText == "Notes") { cell.Width = 400; cell.BackColor = Color.Blue; continue; } if (cell.ContainingField.HeaderText == "RequestedDate") { cell.Width = 130; continue; } } } </script> </head> <body> <form runat="server"> <asp:GridView runat="server" ID="listData" AutoGenerateColumns="True" HorizontalAlign="Left" PageSize="20" OnRowDataBound="GridView_RowDataBound" EmptyDataText="No Data Available." Width="95%"> </asp:GridView> </form> </body> </html> 

有一个小的改变发生,它不会在rowdatabound下,首先所有的行应该绑定,只有这样我们才能隐藏。 所以在grid是dataBound之后它将是一个单独的方法。

请使用此代码。 这使得无形列如果空…

  protected void gridview1_DataBound(object sender, EventArgs e) { Boolean hasData = false; for (int col = 0; col < gridview1.HeaderRow.Cells.Count; col++) { for (int row = 0; row < gridview1.Rows.Count; row++) { if (!String.IsNullOrEmpty(gridview1.Rows[row].Cells[col].Text) && !String.IsNullOrEmpty(HttpUtility.HtmlDecode(gridview1.Rows[row].Cells[col].Text).Trim())) { hasData = true; break; } } if (!hasData) { gridview1.HeaderRow.Cells[col].Visible = false; for (int hiddenrows = 0; hiddenrows < gridview1.Rows.Count; hiddenrows++) { gridview1.Rows[hiddenrows].Cells[col].Visible = false; } } hasData = false; } }