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

[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>
    06public 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>
    06public 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}
  1. 使用方式舉例:Value為我的第二欄DataField。
1protected void Button1_Click(object sender, EventArgs e)
2{
3    this.Button1.Text = this.JoeyGridView1.Rows[1].Cells[this.JoeyGridView1.GetDataFieldColumnIndex("Value")].Text;
4}

转载于:https://www.cnblogs.com/heartstill/archive/2011/12/07/2278924.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值