以下的方法可以根据位名称去找到该列在GridView中对应的 Column 索引,由此索引再去取 GridView 的列;利用此方法的好处是当 GridView 列位有异动(如新增、移动或刪除)时,不需要再更改程序,可以做到通用。
程序如下:
private int GetGridViewColumnIndex(GridView grid, string colName)
{
DataControlField oColField;
int ndx = 0;
foreach (DataControlField oCol in grid.Columns)
{
if (oCol.GetType() == typeof(BoundField))
{
BoundField bfield = (BoundField)oCol;
if (bfield.DataField.ToUpper() == colName.ToUpper())
{
return ndx;
}
}
ndx++;
}
}
{
DataControlField oColField;
int ndx = 0;
foreach (DataControlField oCol in grid.Columns)
{
if (oCol.GetType() == typeof(BoundField))
{
BoundField bfield = (BoundField)oCol;
if (bfield.DataField.ToUpper() == colName.ToUpper())
{
return ndx;
}
}
ndx++;
}
}