ASP.NET - C# 通过HeaderText检索DataGrid单元格






4.20/5 (8投票s)
2005 年 8 月 15 日
2分钟阅读

108044

975
向开发者展示如何通过列HeaderText检索列或单元格。
引言
在之前的文章通过HeaderText隐藏DataGrid列中,我描述了如何通过`HeaderText`隐藏`DataGridColumn`。如果您没有阅读之前的文章,它提供了一种基于用户视图隐藏/显示列的方法。这解决了引用列索引的问题,当您移动列时,这可能会导致问题。本文基于该示例构建,并演示了如何通过列的`HeaderText`检索`DataGrid`中的数据。您现在可以使用标题文本从`DataGrid`填充和检索数据。
我之前遇到了引用列索引的问题。如您所知,用户经常希望在网格中添加、删除和移动列。如果网格中有很多列,这可能会成为一项繁琐的任务。索引难题有一个简单的解决方案。为简单起见,我选择将通过`HeaderText`检索单元格或列的方法包含在页面的类中。在您的应用程序中,您可以选择创建一个自定义`DataGrid`并在其中实现这些方法,或者创建一个每个网格都会调用的辅助类,或者像我一样做。
代码
下面是一个通过`headerText`检索`TableCell`的方法示例。输入参数是`DataGridItem item`和string headerText
。要使用此方法,您需要遍历`DataGridItem`,我将向您展示如何操作。
public TableCell GetCellByHeaderText(DataGridItem item,
string headerText)
{
if(item == null || headerText == null)
{
return null;
}
DataGrid dg = item.NamingContainer as DataGrid;
int colNum = this.GetIndexByHeaderText(dg.Columns,
headerText);
if(colNum >= 0)
{
return item.Cells[colNum];
}
// No cell found by header text.
return null;
}
此方法通过`headerText`检索`DataGridColumn`。输入参数是`DataGrid dg`和string headerText
。
public DataGridColumn GetColumnByHeaderText(DataGrid dg,
string headerText)
{
if(dg == null || dg.Columns == null ||
headerText == null)
{
return null;
}
// Loop through each column in the grid.
foreach(DataGridColumn col in dg.Columns)
{
if(col.HeaderText == headerText)
{
return col;
}
}
// No column found by header text.
return null;
}
此方法检索列的`HeaderText`与传入的`headerText`匹配的列的索引。输入参数是`DataGridColumnCollection cols`和string headerText
。
private int GetIndexByHeaderText(DataGridColumnCollection cols,
string headerText)
{
if(cols == null)
{
return -1;
}
// Loop through each column in the grid.
for(int i=0; i < cols.Count; i++)
{
if(cols[i].HeaderText == headerText)
{
return i;
}
}
// No column found by header text.
return -1;
}
页面代码隐藏
此方法利用上面显示的方法通过`HeaderText`检索数据。它位于页面的代码隐藏类中。该方法循环遍历`DataGrid`中的每个`DataGridItem`。此示例出于演示目的将数据输出回页面。在实际应用程序中,您会将数据存储在数据库中。
private void DisplayDataFromGrid()
{
// Loop through the items in the grid.
foreach(DataGridItem item in this.dgExample2.Items)
{
string name = this.GetCellByHeaderText(item,
"Name").Text;
string title = this.GetCellByHeaderText(item,
"Title").Text;
string phone = this.GetCellByHeaderText(item,
"Phone").Text;
string email = this.GetCellByHeaderText(item,
"Email").Text;
string salary = this.GetCellByHeaderText(item,
"Salary").Text;
string ssnum = this.GetCellByHeaderText(item,
"SS#").Text;
// Write to screen - for testing only...
Response.Write(name);
Response.Write(" | " + title);
Response.Write(" | " + phone);
Response.Write(" | " + email);
Response.Write(" | " + salary);
Response.Write(" | " + ssnum);
Response.Write("<br>");
}
}
结论
通过使用本文和我的上一篇文章中的示例,您不再需要通过索引引用列。您可以使用`HeaderText`进行显示和检索。如果您的`DataGrid`不断修改,这可以节省大量时间。