【问题标题】:GridView Hide Column by codeGridView 按代码隐藏列
【发布时间】:2011-04-18 16:02:48
【问题描述】:

我想在我的 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?请在此处添加您的代码
  • GridView1.DataSource = patientObj.GetAllPatients().Tables[0]; GridView1.DataBind();
  • 而 GetAllPatients() 是一个返回 DataSet 对象的方法
  • 将空数据模板添加到网格视图中查看 patientObj.GetAllPatients().Tables[0] 是否返回空白数据表

标签: c# asp.net


【解决方案1】:

如果您想在填充网格时隐藏该列,您可以像这样在 aspx 页面本身中执行此操作

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

【讨论】:

  • 如果开发人员设置了 AutoGenerateColumns="true",这不是解决方案
【解决方案2】:

当您的 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 事件设置不可见的列。

【讨论】:

    【解决方案3】:

    在这里,我将 gridview 与这样的数据集绑定-

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

    然后

    然后我们统计行数 像这样在for循环中

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

    然后在我们找到我们想要的header之后将其设为false

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

    然后在我们使该特定单元格的可见性为 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); } }

    【讨论】:

      【解决方案4】:

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

      如果您有AutoGenerateColumns = "false" 并且实际上将BoundField 用于您要隐藏的列,那么Bala 的answer 很灵巧。但如果您使用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 想要的,但当我发现自己问同样的问题时,它就是我正在寻找的解决方案。

      【讨论】:

        【解决方案5】:

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

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

        【讨论】:

          【解决方案6】:

          这对我有帮助

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

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

          【讨论】:

          • 但是,如果您想隐藏该列中的控件并且仍然可以在后面的代码中访问它们怎么办? .Visible 从字面上将其从 DOM 中删除。我们需要的是 style="display:none"。
          • @Fandango68...没错!我在 RowDataBound 中为文本着色,需要这个特定的字段存在并被隐藏。
          • 你也可以这样做。 this.myGridview.Columns["columnName"].Visible = false;
          • On Row DataBound 确保它的 DataRow。 if (e.Row.RowType == DataControlRowType.DataRow) { gridviewid.Columns[1].Visible = false; }
          【解决方案7】:

          请使用此代码。如果为空,这会使列不可见...

              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;
          
                  }
          
              }
          

          【讨论】:

            【解决方案8】:
             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
            
                    }
            
            
                }
            

            【讨论】:

              【解决方案9】:

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

              【讨论】:

              【解决方案10】:

              当列 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>
              

              【讨论】:

              • 你不能像那样转换它... System.InvalidCastException: 无法将“System.Web.UI.WebControls.TableCell”类型的对象转换为“System.Web.UI.WebControls”类型.DataControlFieldCell'
              • 显示的更新代码充分证明了它的工作原理。前面的代码示例无法自行证明。
              【解决方案11】:

              如果您想在 GridView 中通过名称而不是索引来隐藏列。创建 DataTable 或 Dataset 后,您必须通过名称找到列的索引,然后将索引保存在 ViewStae、Session 等全局变量中,然后在 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;
                  }                        
              }
              

              【讨论】:

                【解决方案12】:

                这里的大多数答案没有解释的是 - 如果您需要使列再次可见和不可见,这一切都基于动态数据怎么办?毕竟,GridViews 不应该以数据为中心吗?

                如果您想根据您的数据打开或关闭列怎么办?

                我的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”是一个序号。

                我这样做的方式是按照设计隐藏所有列,我知道以后会打开(可见=“真”)或关闭(可见=“假”),并且取决于我的数据。

                在我的情况下,我想将期间时间显示到某一列。例如,如果今天是上午 9 点,那么我想显示上午 6 点、上午 7 点、上午 8 点和上午 9 点的时段,但不显示上午 10 点、上午 11 点等。

                在其他日子我想显示所有时间。以此类推。

                那么我们该怎么做呢?

                为什么不使用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;
                    }
                }
                

                现在根据找到 HeaderText 的开头打开您需要的列,并使列可见如果标题文本不是默认值。

                  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 并使用我想要的标题打开我想要的列。

                所以它的工作方式是,每次您选择不同的日期或时间段显示为标题时,它都会在再次构建 gridview 之前将 GridView 重置为默认标题文本和 Visible="false" 状态。否则,如果没有 PreRender,GridView 将具有先前数据的标题,因为后面的代码会擦除 default 设置。

                【讨论】:

                  【解决方案13】:

                  由于您想隐藏您的列,您可以随时在 gridview 的 preRender 事件中隐藏该列。这有助于您为每行的每个 rowdatabound 事件减少一个操作。预渲染事件只需要一个操作。

                  protected void gvVoucherList_PreRender(object sender, EventArgs e)
                      {
                          try
                          {
                              int RoleID = Convert.ToInt32(Session["RoleID"]);
                  
                              switch (RoleID)
                              {
                                  case 6: gvVoucherList.Columns[11].Visible = false;
                                      break;
                                  case 1: gvVoucherList.Columns[10].Visible = false;
                                      break;
                              }
                              if(hideActionColumn == "ActionSM")
                              {
                                  gvVoucherList.Columns[10].Visible = false;
                                  hideActionColumn = string.Empty;
                              }
                          }
                          catch (Exception Ex)
                          {
                  
                          }
                      }
                  

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 2014-09-09
                    • 2011-08-26
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2011-07-17
                    • 1970-01-01
                    • 2011-04-09
                    相关资源
                    最近更新 更多