[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即可。
- 針對BoundField的DataField屬性,缺點是只有BoundField能用。 view source
print?
02 |
/// Gets the index of the datafield column name matched. |
04 |
/// <param name="DataColumnName">Name of the data column.</param> |
05 |
/// <returns></returns> |
06 |
public int GetDataFieldColumnIndex( string DataColumnName) |
08 |
DataControlFieldCollection Columns = this .Columns; |
10 |
foreach (DataControlField field in Columns) |
12 |
if (field is System.Web.UI.WebControls.BoundField) |
14 |
if (((BoundField)field).DataField == DataColumnName) |
16 |
columnIndex = Columns.IndexOf(field); |
- 針對Column的HeaderText屬性,優點是即使不是BoundField,仍能讀取到該欄。缺點是可能會有中文,或是HeaderText如果是動態或多國語言,有點麻煩。view source
print?
02 |
/// Gets the index of the headertext column name matched. |
04 |
/// <param name="columnHeaderText">The column headertext.</param> |
05 |
/// <returns></returns> |
06 |
public int GetHeaderTextColumnIndex( string columnHeaderText) |
08 |
foreach (DataControlField column in this .Columns) |
10 |
if (column.HeaderText == columnHeaderText) |
12 |
int columnID = this .Columns.IndexOf(column); |
使用方式舉例:Value為我的第二欄DataField。
view source
print?
1 |
protected void Button1_Click( object sender, EventArgs e) |
3 |
this .Button1.Text = this .JoeyGridView1.Rows[1].Cells[ this .JoeyGridView1.GetDataFieldColumnIndex( "Value" )].Text; |