下面方法,只能在Gridview的BoundField进行操作,而在TemplateField模版中去找的话,就无能为力了,因TemplateField模版没有DataField属性。


 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;
        }

或者可以利用HeaderText与FieldName进行比较,返回列索引:


 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;
        }
05-11 12:50