GridView获取值

GridView获取值方法

1.  GridView1.Rows[行号].Cells[列数].Text;

注意列数从0开始,但其属性Visible为false则无法获取


2.  GridView1.DataKeys[行号].Values["FEntryID"].ToString();

GridView需要设定【DataKeyNames】,其可见设置为false,也可以获取


2014-07-30新增

GridView的DataKeyNames属性设为"ID,Name"

GridView1.DataKeyNames = new string[]{ "ID","Name" };

删除事件GridView1_RowDeleting使用:

DataKey key = GridView1.DataKeys[e.RowIndex];
int id = int.Parse(key[0].ToString());//得到id字段值
string name = key[1].ToString();//得到name字段值


取值
string aaa= GridView.DataKeys[e.Row.RowIndex].Value.ToString();


在GridView1_RowDataBound事件中取值

(DataRowView)e.Row.DataItem)["FId"].ToString()


3.  利用列名进行获取

int GetColumnIndexByName(GridViewRow row, string columnName)

{

    int columnIndex = 0;

    foreach (DataControlFieldCellcell in row.Cells)

    {

        if(cell.ContainingField is BoundField)

            if(((BoundField)cell.ContainingField).DataField.Equals(columnName))

                break;

        columnIndex++; //keep adding 1 while we don't have the correct name

    }

    return columnIndex;

}

其获取方式

protected void GridView_RowDataBound(objectsender, GridViewRowEventArgs e)

{

    if (e.Row.RowType == DataControlRowType.DataRow)

    {

        int index = GetColumnIndexByName(e.Row,"myDataField");

        stringcolumnValue = e.Row.Cells[index].Text;

    }

}


4.  对于列为Template的数据获取方式

<asp:GridView ID="gv" runat="server">

    <Columns>

        <asp:TemplateField>

            <ItemTemplate>

                <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>' />

            </ItemTemplate>

        </asp:TemplateField>

    </Columns>

</asp:GridView>


获取值的方式:

string columnValue = ((Label)e.Row.FindControl("lblName")).Text;

 

后两种方式来

http://stackoverflow.com/questions/9715983/how-to-get-the-cell-value-by-column-name-not-by-index-in-gridview-in-asp-net

 

如有更好方法请告诉偶。谢谢

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值