在Gridview控件中根据Field Name来取得对应列索引
下面方法,只能在Gridview的BoundField进行操作,而在TemplateField模版中去找的话,就无能为力了,因TemplateField模版没有DataField属性。
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
public int GetColumnIndex(GridView gridView, string fieldName)
{
int index = -1;
for (int i = 0; i < gridView.Columns.Count; i++)
{
DataControlField dataControlField = gridView.Columns[i];
BoundField boundField = dataControlField as BoundField;
if (boundField != null && boundField.DataField == fieldName)
index = i;
}
return index;
}
{
int index = -1;
for (int i = 0; i < gridView.Columns.Count; i++)
{
DataControlField dataControlField = gridView.Columns[i];
BoundField boundField = dataControlField as BoundField;
if (boundField != null && boundField.DataField == fieldName)
index = i;
}
return index;
}
或者可以利用HeaderText与FieldName进行比较,返回列索引:
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
public int GetColumnIndex(GridView gridview, string fieldName)
{
int index = -1;
foreach (DataControlField dataControlField in gridview.Columns)
{
if (dataControlField.HeaderText == fieldName)
{
index = gridview.Columns.IndexOf(dataControlField);
}
}
return index;
}
{
int index = -1;
foreach (DataControlField dataControlField in gridview.Columns)
{
if (dataControlField.HeaderText == fieldName)
{
index = gridview.Columns.IndexOf(dataControlField);
}
}
return index;
}