heartstill

博客园 首页 新随笔 联系 订阅 管理

[ASP.NET]GridView的Row.Cells[ColumnIndex]如何改用ColumnName來使用

有用過DataGrid的人,一定記得之前是可以直接讀取Cell(string ColumnName)的。

這個東西,在GridView卻消失了,e.Row.Cells[int ColumnIndex],只能用Index去取得欄位的位置。

這在程式需求變動頻繁或需要合併儲存格、合併Grid Header等,用index算是相當麻煩的,往往多一個Column,index調到手軟,還會miss。

 

所以,這個需求其實在大專案開發還是蠻有必要設計的。

可惜的是,似乎沒找到直接拓展Cells()的方式,(好想設計成多載啊~~~~)

網路上與MS論壇,幾乎都是額外用function轉,當然效率一定是比較差的,但一個Grid的Columns正常來講應該不多,

效率與維護成本一比,恩,還是寫個function來得好用一點。

 

這邊提供兩個版本,前提都是ColumnName不能有重複的,function我是直接設計在GridView裡面。

不想寫在GridView裡面的,就把this改成自己的GridView的ID即可。

  1. 針對BoundField的DataField屬性,缺點是只有BoundField能用。
    01 /// <summary>
    02 /// Gets the index of the datafield column name matched.
    03 /// </summary>
    04 /// <param name="DataColumnName">Name of the data column.</param>
    05 /// <returns></returns>
    06 public int GetDataFieldColumnIndex( string DataColumnName)
    07 {
    08     DataControlFieldCollection Columns = this.Columns;
    09     int columnIndex = -1;
    10     foreach (DataControlField field in Columns)
    11     {
    12         if (field is System.Web.UI.WebControls.BoundField)
    13         {
    14             if (((BoundField)field).DataField == DataColumnName)
    15             {
    16                 columnIndex = Columns.IndexOf(field);
    17             }
    18         }
    19     }
    20     return columnIndex;
    21 }
  2. 針對Column的HeaderText屬性,優點是即使不是BoundField,仍能讀取到該欄。缺點是可能會有中文,或是HeaderText如果是動態或多國語言,有點麻煩。
    01 /// <summary>
    02 /// Gets the index of the headertext column name matched.
    03 /// </summary>
    04 /// <param name="columnHeaderText">The column headertext.</param>
    05 /// <returns></returns>
    06 public int GetHeaderTextColumnIndex(string columnHeaderText)
    07 {
    08     foreach (DataControlField column in this.Columns)
    09     {
    10         if (column.HeaderText == columnHeaderText)
    11         {
    12             int columnID = this.Columns.IndexOf(column);
    13             return columnID;
    14         }
    15     }
    16     return -1;
    17 }
    使用方式舉例:Value為我的第二欄DataField。
    1 protected void Button1_Click(object sender, EventArgs e)
    2 {
    3     this.Button1.Text = this.JoeyGridView1.Rows[1].Cells[this.JoeyGridView1.GetDataFieldColumnIndex("Value")].Text;
    4 }
posted on 2011-12-07 11:03  开始测试  阅读(536)  评论(0编辑  收藏  举报