代码之家  ›  专栏  ›  技术社区  ›  amr osama

GridView按代码隐藏列

  •  29
  • amr osama  · 技术社区  · 14 年前

    GridView1.Columns[0].Visible = false;
    

    但令人惊讶的是,我的伯爵财产为我的 GridView 列为0!!!而我可以看到 网格视图 ,有什么想法吗?

    更新:

    下面是填充 网格视图

    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;
    
    }
    
    13 回复  |  直到 8 年前
        1
  •  68
  •   Brissles    9 年前

    GridView.Columns.Count AutoGenerateColumns 属性设置为 true 是的

    自动生成列 属性到 false ,也可以在代码隐藏中使用:

    GridView.Rows[0].Cells.Count

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

    使用GridView的 RowDataBound 事件。

        2
  •  32
  •   Ankur    11 年前

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

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

        3
  •  26
  •   Zain Shaikh    12 年前

    ((DataControlField)gridView.Columns
                   .Cast<DataControlField>()
                   .Where(fld => (fld.HeaderText == "Title"))
                   .SingleOrDefault()).Visible = false;
    
        4
  •  12
  •   Community uzul    7 年前

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

    AutoGenerateColumns = "false" 实际上是在使用 BoundField 你想隐藏的专栏,巴拉的 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
  •  3
  •   Zain Shaikh    12 年前

    在这里,我将gridview与如下数据集绑定-

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

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

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

        6
  •  2
  •   Bala    14 年前

    <asp:BoundField DataField="test" HeaderText="test" Visible="False" />
    
        7
  •  2
  •   rithish    11 年前
     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
    
            }
    
    
        }
    
        8
  •  2
  •   Parsa    10 年前

    如果您想在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;
        }                        
    }
    
        9
  •  2
  •   Fandango68    8 年前

    这里大多数答案没有解释的是——如果您需要使列再次可见和不可见,所有这些都是基于动态数据的,该怎么办?毕竟,我不应该 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点, 但不是

    在其他日子里,我想一直展示。等等。

    那我们怎么做呢?

    PreRender 重新设置 ?

    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 ,我可以重置 GridView 然后用我想要的标题打开我想要的列。

    gridview 再一次。否则,没有 预渲染 违约 设置。

        10
  •  0
  •   James    9 年前

    <%@ 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>
    
        11
  •  0
  •   BangEqualsDestructor    8 年前

    有一个小的变化发生,它将不会在rowdatabound下,首先所有的行应该得到绑定,只有这样我们才能隐藏。因此,在网格数据绑定之后,它将是一个单独的方法。

        12
  •  0
  •   Kalu Singh Rao    8 年前

    请使用此代码。如果为空,则此列将变为不可见列。。。

        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;
    
            }
    
        }
    
        13
  •  0
  •   Saronyo    6 年前

    因为要隐藏列,所以可以始终在gridview的preRender事件中隐藏该列。这有助于为每行的每个rowdatabound事件减少一个操作。prerender事件只需要一个操作。

    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)
            {
    
            }
        }