我在 Dbhelper 里面写了 一 个  gridview 绑定表的方法,在add页面调用 
但怎么更改  gridview 显示出来的表头啊 ? 在 dehelper.cs页面 public static DataTable Bind()
    {
        SqlConnection conn = DbHelp.creatConn();
        conn.Open();
        SqlDataAdapter sda = new SqlDataAdapter();
        sda.SelectCommand = new SqlCommand("select p_user,p_pass from t_user", conn);
        DataSet ds = new DataSet();
        sda.Fill(ds, "t_user");
        return ds.Tables["t_user"];
    }在add.cs页面调用方法的代码
gridview的前台代码
<asp:GridView ID="GridView1" runat="server" align="center">
    </asp:GridView>后台代码
 public void grid()
    {
        this.GridView1.DataSource = DbHelp.Bind();
        this.GridView1.DataBind();
    }
用模板列的话就要指定数据库库中的字段,但是 我的gridview是一个 ,在不同情况下绑定不同的表,所以表头不相同,所以用模板列好像行不通,
有人说在bind之前指定表头public void grid()
    {
        this.GridView1.DataSource = DbHelp.Bind();
        GridView1.Columns[0].HeaderText = "性别"; 
        GridView1.Columns[1].HeaderText = "名字"; 
        this.GridView1.DataBind();
    }
但是 我这样做有错
GridView2.Columns[1].HeaderText = "名字"; 
索引超出范围。必须为非负值并小于集合大小。 
参数名: index怎么办?

解决方案 »

  1.   

    写在dataBound事件里面其实大可以放心的使用模板列来实现!!
      

  2.   

    public void grid()
        {
            this.GridView1.DataSource = DbHelp.Bind();
            GridView1.Columns[0].HeaderText = "性别"; 
            GridView1.Columns[1].HeaderText = "名字"; 
            this.GridView1.DataBind();
        }
    这个代码错误很明显这时候gridview1里面还没有数据
      

  3.   

    AutoGenerateColumns = true; 表示为数据源中的每个字段自动创建绑定字段
    可使用ITemplate
    ds.Tables[0].Columns[0].ColumnName = "性别";
      

  4.   

    也可以在GeidView的RowCreated事件中进行,如下
        protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                TableCellCollection cells1 = e.Row.Cells;
                for (int i = 0; i < cells1.Count; i++)
                {
                    cells1[i].Wrap = false;
                    if(i==0)
                       cells1[0].Text="性别"; 
                    else if(i==1)
                       cells1[1].Text="名字"; 
                 }
            }
        }
      

  5.   

    请问
    ds.Tables[0].Columns[0].ColumnName = "性别";
    要写在哪里?
      

  6.   


     protected void GrvBind_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                TableCellCollection cell = e.Row.Cells;
                for (int i = 0; i < cell.Count; i++)
                {
                    cell[i].Wrap = true;
                    switch (i)
                    {
                        case 0:
                            cell[0].Text = "姓名";
                            break;
                        case 1:
                            cell[1].Text = "性别";
                            break;
                    }
                  
                }
            }
        }