c# – 获取GridView列标题文本 – 始终返回空白

我有一个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;
}

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...