按名称查找GridView列索引的方法
我正在尝试编写一个小方法来循环并通过其索引查找GridView
列,因为它可以根据可见的内容更改位置。
这是我到目前为止:
private int GetColumnIndexByName(GridView grid, string name) { foreach (DataColumn col in grid.Columns) { if (col.ColumnName.ToLower().Trim() == name.ToLower().Trim()) return col.Ordinal; } return -1; }
在这种情况下,DataColumn似乎不是正确使用的类型,但我有点迷失在这里我应该做什么。
我只能使用.NET 2.0 / 3.5。 我不能用4.0。
我想通了,我需要使用DataControlField
和稍微不同的语法。
工作版本:
private int GetColumnIndexByName(GridView grid, string name) { foreach (DataControlField col in grid.Columns) { if (col.HeaderText.ToLower().Trim() == name.ToLower().Trim()) { return grid.Columns.IndexOf(col); } } return -1; }
我更喜欢集合迭代,但为什么要在这种情况下打扰foreach
和grid.Columns.IndexOf
调用的开销呢? 只需使用索引遍历数组。
private int GetColumnIndexByName(GridView grid, string name) { for(int i = 0; i < grid.Columns.Count; i++) { if (grid.Columns[i].HeaderText.ToLower().Trim() == name.ToLower().Trim()) { return i; } } return -1; }
更好的解决方案适用于Datafield,SortExpression和headerText。
public static int GetBoundFieldIndexByName(this GridView gv,string name) { int index = 0; bool found = false; foreach (DataControlField c in gv.Columns) { if (c is BoundField) { BoundField field = (BoundField)c; if (name == field.DataField || name == field.SortExpression || name == field.HeaderText) { found = true; break; } } index++; } return found ? index : -1; }
这样,对我有用(.NET Gridview):
private int GetColumnIndexByName(GridView grid, string name) { for (int i = 0; i < grid.HeaderRow.Cells.Count; i++) { if (grid.HeaderRow.Cells[i].Text.ToLower().Trim() == name.ToLower().Trim()) { return i; } } return -1; }
//Get index of column by header text. int GetColumnIndexByName(GridViewRow row, string headerText) { int columnIndex = 0; foreach (DataControlFieldCell cell in row.Cells) { if(cell.ContainingField is TemplateField){ if(((TemplateField)cell.ContainingField).HeaderText.Equals(headerText)) { break; } } if(cell.ContainingField is BoundField){ if (((BoundField)cell.ContainingField).HeaderText.Equals(headerText)) { break; } } columnIndex++; } return columnIndex; }
如果您需要一个列本身而不仅仅是它的索引,您可以使用一些Linq魔法:
DataControlField col=GridView1.Columns.Cast().First(c => c.HeaderText == "Column_header")