2013-12-17 40 views
0

我想提取gridview的列名并使用下拉列表将这些列名绑定到一个过滤器模板。我在页面加载事件中从gridview获取列名时遇到了一些挑战。以下是我正在尝试的错误代码。如何获取与SqlDataSource绑定的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循环添加此对每列

注:有一些隐藏的(visible = FALSE)领域也是在GridView控件

+0

你的DGV绑定到一个DataTable? – NoChance

+0

这是asp.net网格视图: Vicky

+0

但是什么是数据源? – NoChance

回答

0

你可以在2种方式(至少)列名:

1 - 使用DataGrid本身:

  //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+","; 
     } 
相关问题