注意是列索引 为什么要获得列索引:因为我要在下面事件中根据列索引去隐藏列 可是我只知道 绑定列的字段名 不知道这个字段的cells索引值 
(因为列是自动创建的所以无法去数他的cells是第几)protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow ||
        e.Row.RowType == DataControlRowType.Header)
        {
            e.Row.Cells[这个值怎么根据字段名得到].Visible = false; //
        }
    }由于绑定gridview的列是自动创建的 用下面方法试过了自动创建的列在下面这个事件里面是找不到e.Row.Cells[i].Text的文本值 这个值永远为空protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        int index = -1;
        if (e.Row.RowType == DataControlRowType.Header)
        {
            for (int i = 0; i < e.Row.Cells.Count; i++)
            {
                 // 不是字段名,是字段对应的列的列名
                if (e.Row.Cells[i].Text == "特定列名")
                {
                    e.Row.Cells[i].Visible = false;
                    index = i;
                }
            }
        }
        else if (e.Row.RowType == DataControlRowType.DataRow)
        {
            for (int i = 0; i < e.Row.Cells.Count; i++)
            {
                if (i == index)                
                {
                    e.Row.Cells[i].Visible = false;                    
                }
            }
        }
}

解决方案 »

  1.   

    已经为了这个问题发了一个帖子 请高手不吝赐教
    http://topic.csdn.net/u/20080514/11/f8eb3b16-9df3-4eb7-bb22-32fb600b7212.html?956222352#replyachor
      

  2.   


    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="testGridView.aspx.cs" Inherits="testGridView" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>无标题页</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:GridView ID="gv" runat="server" AutoGenerateColumns="False" OnRowDataBound="gv_RowDataBound">
            </asp:GridView>
        
        </div>
        </form>
    </body>
    </html>
    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;public partial class testGridView : System.Web.UI.Page
    {
        int index = -1;
        protected DataTable getDataTable()
        {        System.Data.DataTable dt = new System.Data.DataTable();
            System.Data.DataRow dr;
            dt.Columns.Add(new System.Data.DataColumn("Name", typeof(System.String)));
            dt.Columns.Add(new System.Data.DataColumn("Unit", typeof(System.String)));
            dt.Columns.Add(new System.Data.DataColumn("Standard", typeof(System.String)));
            dt.Columns.Add(new System.Data.DataColumn("Quantity", typeof(System.Int32)));
            dr = dt.NewRow();
            dr[0] = "黑色圆珠笔";
            dr[1] = "枝";
            dr[2] = "2*2";
            dr[3] = 10;
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr[0] = "红色圆珠笔";
            dr[1] = "枝";
            dr[2] = "2*2";
            dr[3] = 15;
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr[0] = "黄色圆珠笔";
            dr[1] = "枝";
            dr[2] = "2*2";
            dr[3] = 20;
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr[0] = "蓝色圆珠笔";
            dr[1] = "枝";
            dr[2] = "2*2";
            dr[3] = 18;
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr[0] = "辰光签字笔";
            dr[1] = "枝";
            dr[2] = "2*2";
            dr[3] = 15;
            dt.Rows.Add(dr);
            return dt;
        }    private void createColumn(GridView gv)
        {
            BoundField bf = new BoundField();
            bf.HeaderText = "名称";
            bf.DataField = "Name";
            gv.Columns.Add(bf);
            bf = new BoundField();
            bf.HeaderText = "单位";
            bf.DataField = "Unit";
            gv.Columns.Add(bf);
            bf = new BoundField();
            bf.HeaderText = "数量";
            bf.DataField = "Quantity";
            gv.Columns.Add(bf);
        }    protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                createColumn(gv);
                gv.DataSource = getDataTable();
                gv.DataBind();
            }
        }
        protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            
            if (e.Row.RowType == DataControlRowType.Header)
            {
                for (int i = 0; i < e.Row.Cells.Count; i++)
                {
                    // 不是字段名,是字段对应的列的列名
                    if (e.Row.Cells[i].Text == "名称")
                    {
                        e.Row.Cells[i].Visible = false;
                        index = i;
                    }
                }
            }
            else if (e.Row.RowType == DataControlRowType.DataRow)
            {
                for (int i = 0; i < e.Row.Cells.Count; i++)
                {
                    if (i == index)
                    {
                        e.Row.Cells[i].Visible = false;
                    }
                }
            }    }
    }
      

  3.   

    OnDataBound:
        protected void GridView1_DataBound(object sender, EventArgs e)
        {
            for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
            {
                if (GridView1.HeaderRow.Cells[i].Text == "字段名")
                    GridView1.Columns[i].Visible = false;
            }
        }
      

  4.   

    当时回复你那个帖子 没测试,有个逻辑错误。
    int index = -1;
    位置的问题。这回你试下
      

  5.   


    我的gridview的这个属性是 AutoGenerateColumns="True" 这会影响你上面的例子的效果吗?
      

  6.   


    ======这个你测试了? 好像index现在变成没定义了吧?
      

  7.   

    那你就需要根据数据源 例如datatable的列名来控制了
    if (e.Row.Cells[i].Text == "名称")下面这个是控制数据源中列名为Name 的if (e.Row.Cells[i].Text == "Name")
      

  8.   


    int index = -1;
        protected DataTable getDataTable()
        {没注意吧?
      

  9.   

    你说的是不是这东西?
    GridView1.DataKeyNames = new string[] { "ID" };
    学习楼主的学习精神!!
      

  10.   


    还是一样不行。。固定的几列能得到 头名 可是 后面自动创建的列 if (e.Row.Cells[i].Text == "")的值都是为空<asp:GridView ID="GridView1" runat="server" OnSorting="GridView1_Sorting" AllowSorting="True"                                    Width="100%" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound"
                                        CssClass="border" OnRowCreated="GridView1_RowCreated">
                                        <AlternatingRowStyle HorizontalAlign="Center" CssClass="dbtable_data1" />
                                        <RowStyle HorizontalAlign="Center" CssClass="dbtable_data2" VerticalAlign="Middle"></RowStyle>
                                        <HeaderStyle CssClass="dbtable_title"></HeaderStyle>
                                        <FooterStyle HorizontalAlign="Center" VerticalAlign="Middle"></FooterStyle>
                                        <Columns>
                                            <asp:TemplateField HeaderText="编号">
                                            <HeaderStyle Width="2px" />
                                            <ItemStyle Width="2px" />
                                                <ItemTemplate>
                                                    <asp:Label ID="lblNum" runat="server" Text='<%# Container.DataItemIndex + 1 %>'></asp:Label>
                                                </ItemTemplate>
                                            </asp:TemplateField>
                                            <asp:TemplateField HeaderText="编辑">
                                                <HeaderStyle Width="40px" />
                                                <ItemTemplate>
                                                    <asp:LinkButton ID="LinkButtonEdit" runat="server" CommandName="edititem" CommandArgument='<%# Eval(PKField) %>'>
                                                        <asp:Image runat="server" AlternateText="编辑" ID="Image1" ImageUrl="~/img/modify.gif">
                                                        </asp:Image>
                                                    </asp:LinkButton>
                                                </ItemTemplate>
                                            </asp:TemplateField>
                                            <asp:TemplateField HeaderText="删除">
                                                <HeaderStyle Width="40px"></HeaderStyle>
                                                <ItemTemplate>
                                                    <asp:LinkButton ID="LinkButtonDelete" runat="server" CommandName="deleteitem" CommandArgument='<%# Eval(PKField) %>'>
                                                        <asp:Image ID="Image2" runat="server" ImageUrl="~/img/delete.gif" AlternateText="删除">
                                                        </asp:Image>
                                                    </asp:LinkButton>
                                                </ItemTemplate>
                                            </asp:TemplateField>
                                            <asp:TemplateField HeaderText="查看">
                                                <HeaderStyle Width="40px"></HeaderStyle>
                                                <ItemTemplate>
                                                    <asp:LinkButton ID="LinkButtonLook" runat="server" CommandName="lookitem" CommandArgument='<%# Eval(PKField) %>'>
                                                        <asp:Image ID="Image3" runat="server" ImageUrl="~/img/look.gif" AlternateText="查看详细">
                                                        </asp:Image>
                                                    </asp:LinkButton>
                                                </ItemTemplate>
                                            </asp:TemplateField>
                                           </Columns>
                                        <SelectedRowStyle BackColor="Cyan" CssClass="dbtable_data3" />
                                    </asp:GridView>
      

  11.   


    不是这个问题。。是绑定完一个自动创建列后的gridview怎么去隐藏 某一个列。。
      

  12.   


    我知道是要用数据源中列名 关键是 。。e.Row.Cells[i].Text 得到值都是为空不知道你有没有试着 跟踪看下这个值。。(除了前面几个固定的模板列,后面自动创建的列这个值全部是为空的 不知道在RowDataBound事件里面是不是无法得到 自动创建的列的这个值?
      

  13.   

    你运行我写的DEMO了么我也是动态创建的列。问题的关键是 动态创建的列,你需要给它指定列名不指定的话,它当然是空了。指定列名就两个办法 一是指定GridView中的列的列名二是指定绑定数据源的列名根据指定的列名在去判断 做操作
      

  14.   


    ==========关键是这个属性AutoGenerateColumns="False" 你把这个改为true你就知道我说的是什么意思啦 数据源取出来后直接自动创建列。。
      

  15.   


    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="testGridView.aspx.cs" Inherits="testGridView" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>无标题页</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:GridView ID="gv" runat="server" AutoGenerateColumns="true" OnRowDataBound="gv_RowDataBound">
            </asp:GridView>
        
        </div>
        </form>
    </body>
    </html>using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;public partial class testGridView : System.Web.UI.Page
    {    
        string index = "";
        string columnStr = "";    protected DataTable getDataTable()
        {        System.Data.DataTable dt = new System.Data.DataTable();
            System.Data.DataRow dr;
            dt.Columns.Add(new System.Data.DataColumn("Name", typeof(System.String)));
            dt.Columns.Add(new System.Data.DataColumn("Unit", typeof(System.String)));
            dt.Columns.Add(new System.Data.DataColumn("Standard", typeof(System.String)));
            dt.Columns.Add(new System.Data.DataColumn("Quantity", typeof(System.Int32)));
            dr = dt.NewRow();
            dr[0] = "黑色圆珠笔";
            dr[1] = "枝";
            dr[2] = "2*2";
            dr[3] = 10;
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr[0] = "红色圆珠笔";
            dr[1] = "枝";
            dr[2] = "2*2";
            dr[3] = 15;
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr[0] = "黄色圆珠笔";
            dr[1] = "枝";
            dr[2] = "2*2";
            dr[3] = 20;
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr[0] = "蓝色圆珠笔";
            dr[1] = "枝";
            dr[2] = "2*2";
            dr[3] = 18;
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr[0] = "辰光签字笔";
            dr[1] = "枝";
            dr[2] = "2*2";
            dr[3] = 15;
            dt.Rows.Add(dr);
            return dt;
        }    private void createColumn(GridView gv)
        {
            BoundField bf = new BoundField();
            bf.HeaderText = "名称";
            bf.DataField = "Name";
            gv.Columns.Add(bf);
            bf = new BoundField();
            bf.HeaderText = "单位";
            bf.DataField = "Unit";
            gv.Columns.Add(bf);
            bf = new BoundField();
            bf.HeaderText = "数量";
            bf.DataField = "Quantity";
            gv.Columns.Add(bf);
        }    protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //设置要隐藏列的列名
                columnStr = "Name,名称";
                createColumn(gv);
                gv.DataSource = getDataTable();
                gv.DataBind();
            }
        }
        protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            
            if (e.Row.RowType == DataControlRowType.Header)
            {
                for (int i = 0; i < e.Row.Cells.Count; i++)
                {
                    // 不是字段名,是字段对应的列的列名
                    if (columnStr.Contains(e.Row.Cells[i].Text))// == "单位")
                    {
                        e.Row.Cells[i].Visible = false;
                        index += "," + i;
                    }
                }
            }
            else if (e.Row.RowType == DataControlRowType.DataRow)
            {
                for (int i = 0; i < e.Row.Cells.Count; i++)
                {
                    if (index.Contains(i.ToString()))
                    {
                        e.Row.Cells[i].Visible = false;
                    }
                }
            }    }
    }
      

  16.   


    <asp:GridView ID="GridView1" runat="server" OnSorting="GridView1_Sorting" AllowSorting="True"  Width="100%" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound"
                                        CssClass="border" OnRowCreated="GridView1_RowCreated">
                                        <AlternatingRowStyle HorizontalAlign="Center" CssClass="dbtable_data1" />
                                        <RowStyle HorizontalAlign="Center" CssClass="dbtable_data2" VerticalAlign="Middle"></RowStyle>
                                        <HeaderStyle CssClass="dbtable_title"></HeaderStyle>
                                        <FooterStyle HorizontalAlign="Center" VerticalAlign="Middle"></FooterStyle>
                                        <Columns>
                                            <asp:TemplateField HeaderText="编号">
                                            <HeaderStyle Width="2px" />
                                            <ItemStyle Width="2px" />
                                                <ItemTemplate>
                                                    <asp:Label ID="lblNum" runat="server" Text='<%# Container.DataItemIndex + 1 %>'></asp:Label>
                                                </ItemTemplate>
                                            </asp:TemplateField>
                                            <asp:TemplateField HeaderText="编辑">
                                                <HeaderStyle Width="40px" />
                                                <ItemTemplate>
                                                    <asp:LinkButton ID="LinkButtonEdit" runat="server" CommandName="edititem" CommandArgument='<%# Eval(PKField) %>'>
                                                        <asp:Image runat="server" AlternateText="编辑" ID="Image1" ImageUrl="~/img/modify.gif">
                                                        </asp:Image>
                                                    </asp:LinkButton>
                                                </ItemTemplate>
                                            </asp:TemplateField>
                                            <asp:TemplateField HeaderText="删除">
                                                <HeaderStyle Width="40px"></HeaderStyle>
                                                <ItemTemplate>
                                                    <asp:LinkButton ID="LinkButtonDelete" runat="server" CommandName="deleteitem" CommandArgument='<%# Eval(PKField) %>'>
                                                        <asp:Image ID="Image2" runat="server" ImageUrl="~/img/delete.gif" AlternateText="删除">
                                                        </asp:Image>
                                                    </asp:LinkButton>
                                                </ItemTemplate>
                                            </asp:TemplateField>
                                            <asp:TemplateField HeaderText="查看">
                                                <HeaderStyle Width="40px"></HeaderStyle>
                                                <ItemTemplate>
                                                    <asp:LinkButton ID="LinkButtonLook" runat="server" CommandName="lookitem" CommandArgument='<%# Eval(PKField) %>'>
                                                        <asp:Image ID="Image3" runat="server" ImageUrl="~/img/look.gif" AlternateText="查看详细">
                                                        </asp:Image>
                                                    </asp:LinkButton>
                                                </ItemTemplate>
                                            </asp:TemplateField>
                                           </Columns>
                                        <SelectedRowStyle BackColor="Cyan" CssClass="dbtable_data3" />
                                    </asp:GridView>
    用上面这个gridview去绑定pubs数据库里面的titles表的title列 你就会发现我说的问题。。
      

  17.   

    其实 我在7楼就已经答复你了~
    不过上面这个DEMO 需要注意一个地方 就是当GridView的列超过10列时
    需要换一个算法,来判断要隐藏那几列因为现在是用字符串的方法来判断
      

  18.   


    用上面这个gridview去绑定pubs数据库里面的titles表的title列 你就会发现我说的问题。。>>用上面这个gridview去绑定pubs数据库里面的titles表 去隐藏的title列 你就会发现我说的问题。。
      

  19.   


    我想请问下 如果我直接从数据库取出数据来绑定 gridview 这种情况gridview的头名是不是就相当于数据库表的字段名 这没错吧。。
    你上面的列子是隐藏的固定的列 而不是去隐藏的自动创建的列 
      

  20.   


    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Data.SqlClient;using System.Collections.Generic;public partial class testGridView : System.Web.UI.Page
    {    
        List<int> lInt = new List<int>();
        List<string> lStr = new List<string>();    SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=pubs;User ID=sa;pwd=sa");    protected void Page_Load(object sender, EventArgs e)
        {
                    if (!IsPostBack)
            {
                SqlDataAdapter da = new SqlDataAdapter("select * from titles", con);
                DataSet ds = new DataSet();
                da.Fill(ds, "titles");
                //设置要隐藏列的列名
                //lStr.Add("title");
                //lStr.Add("title_id");
                lStr.Add("price");
                //columnStr = "Name,title_id";
                //createColumn(gv);
                //gv.DataSource = getDataTable();
                gv.DataSource = ds.Tables["titles"].DefaultView;
                gv.DataBind();
            }
        }
        protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            
            if (e.Row.RowType == DataControlRowType.Header)
            {
                for (int i = 0; i < e.Row.Cells.Count; i++)
                {
                    for (int j = 0; j < lStr.Count; j++)
                    {
                        if (lStr[j] == e.Row.Cells[i].Text)
                        {
                            e.Row.Cells[i].Visible = false;
                            lInt.Add(i);
                        }                
                    }
                    //// 不是字段名,是字段对应的列的列名
                    //if (columnStr.Contains(e.Row.Cells[i].Text))// == "单位")
                    //{
                    //    e.Row.Cells[i].Visible = false;
                    //    index += "," + i;
                    //}  
                }
            }
            else if (e.Row.RowType == DataControlRowType.DataRow)
            {
                for (int i = 0; i < e.Row.Cells.Count; i++)
                {
                    for (int j = 0; j < lInt.Count; j++)
                    {
                        if (lInt[j] == i)
                        {
                            e.Row.Cells[i].Visible = false;                        
                        }  
                    }                //if (index.Contains(i.ToString()))
                    //{
                    //    e.Row.Cells[i].Visible = false;
                    //}
                }
            }    }
    }
      

  21.   

    希望你能试试“用上面这个gridview(18楼的)去绑定pubs数据库里面的titles表 然后去隐藏title列 你就会发现我说的问题。。”
    用 e.Row.Cells[i].Text == "title" 
      

  22.   

    实际上 你只要改变一下sql 语句 就能实现想要的效果~
    没必要这样烦琐的
      

  23.   


    我单独试了你的例子 确实是可以隐藏的 可我的页面上这样用却不行。。
    e.Row.Cells[i].Text 从第4列开始就为空了。。我郁闷
    不知道是不是跟用了 updatepanel有关系。或者是我哪里弄错了。。我再查一下。。
      

  24.   

    汉化也一样的可能你这次是select * from [tableName] 这样全查(ps: 不要写* 要写想查的列名,* 是不好的习惯,我偷个懒。)之后需要隐藏几列,那你只要把想显示的列查询出来就可以了select [columnName],[columnName],... from [tableName]
      

  25.   

    没发现2楼代码有什么问题,正确
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>无标题页</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1" runat="server" OnDataBound="GridView1_DataBound" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="true">
            </asp:GridView>
            </div>
        </form>
    </body>
    </html>
        private int index = -1;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                string strCn = System.Configuration.ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString;
                string strSQL = @"SELECT * FROM [UserInfo]";
                SqlDataAdapter sda = new SqlDataAdapter(strSQL, strCn);
                DataTable dt = new DataTable();
                sda.Fill(dt);
                GridView1.DataSource = dt.DefaultView;
                GridView1.DataBind();
            }
        }    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //int index = -1;
            if (e.Row.RowType == DataControlRowType.Header)
            {
                index = -1;
                for (int i = 0; i < e.Row.Cells.Count; i++)
                {
                    // 不是字段名,是字段对应的列的列名
                    if (e.Row.Cells[i].Text == "Sex")
                    {
                        e.Row.Cells[i].Visible = false;
                        index = i;
                    }
                }
            }
            else if (e.Row.RowType == DataControlRowType.DataRow && index != -1)
            {
                e.Row.Cells[index].Visible = false;
            }
        }这样确实可以隐藏“Sex”列,已验证
      

  26.   

    这个帖子早就看过了,其实这类的问题大多如二楼在RowDataBound或者RowCreated事件中处理,但楼主开始对问题的描述不足够清楚, 比如现在又提到的UpdatePanel..
      

  27.   

    protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
     {
         if (e.Row.RowType == DataControlRowType.DataRow)
            {
         for (int i = 0; i < e.Row.Cells.Count; i++)
        {
           string s=((TextBox)DataBinder.Eval(e.DataItem,"这里写你要隐藏的字段名").ToString()).Text;
           if(e.row.cells[i].text==s)
          {
           e.Row.Cells[i].Visible = false; 
          }           
         }
       }
    你按我上面的方法做,应该是可以的.如果不可以,那就是
    ((TextBox)DataBinder.Eval(e.DataItem,"这里写你要隐藏的字段名").ToString())这句的语法有错,因为我是凭记忆写上去的.