我有一个GridView,我想从列标题的文本.
for (int j = 0; j < grdToDisplay.HeaderRow.Cells.Count; j++) { string s = grdToDisplay.HeaderRow.Cells[j].Text.ToString(); //Returns "" s = grdToDisplay.HeaderRow.Cells[j].Text; //Returns "" s = grdToDisplay.Rows[0].Cells[j].Text; //Returns text from first row of results not the header // s = grdToDisplay.Columns[j].HeaderText.ToString(); // does not work as column count is 0 }
GridView内容是在运行时根据用户查询生成的.标题可单击以进行排序.
如何循环GridView并列出列标题文本?
解决方法
你可以使用
GridViewColumn.HeaderText
for (int i = 0; i < grdToDisplay.Columns.Count; i++) { string header = grdToDisplay.Columns[i].HeaderText; }
编辑:
but this would give me no results as the columns count is 0
然后你有AutoGenerateColumns = true并且只计算声明性添加的列.因此,在对GridView进行数据绑定后使用此代码:
for (int i = 0; i < grdToDisplay.HeaderRow.Cells.Count; i++) { string header = grdToDisplay.HeaderRow.Cells[i].Text; }