如何获取与SqlDataSource绑定的gridview表的表头/列名

问题描述 投票:0回答:1

我想提取 gridview 的列名并将这些列名与下拉列表绑定以制作过滤器模板。我在页面加载事件中从 gridview 获取列名称几乎没有挑战。下面是我正在尝试的错误代码。

和“索引超出范围。必须为非负数且小于集合的大小。 参数名称:索引“

Response.Write(GridView1.Rows[0].Cells[0].Text.ToString());
Response.Write(GridView1.Rows[0].Cells[1].Text.ToString());
Response.Write(GridView1.Rows[0].Cells[2].Text.ToString());
Response.Write(GridView1.Rows[0].Cells[3].Text.ToString());

上面的代码不起作用,如果它起作用,我可以在每列的 foreach 循环中添加它

注意:gridview 中也有一些隐藏(visible=false)字段

c# asp.net sql gridview
1个回答
0
投票

您可以通过两种方式(至少)获取列名:

1-使用数据网格本身:

            //assuming you have a dataset with 1 datatable
            ds.Tables.Add(dt);
            this.GridView1.DataSource=ds;
            DataBind();
            //after binding is complete
            this.headerNames.Text="";

            foreach (var c in GridView1.HeaderRow.Cells)
            {
                this.headerNames.Text += (((System.Web.UI.WebControls.DataControlFieldCell)(c)).ContainingField).HeaderText+",";
            }

2-使用绑定源(在您的情况下是数据表)

        //After you load the datatable from the data source
        this.headerNames.Text = "";
        foreach (DataColumn dc in dt.Columns)
        {
            this.headerNames.Text += dc.ColumnName+",";
        }
© www.soinside.com 2019 - 2024. All rights reserved.