在Gridview控件中根据Field Name来取得对应列索引

下面方法,只能在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;
        }

 

 

posted @ 2010-04-28 10:39  Insus.NET  阅读(1585)  评论(3编辑  收藏  举报