GridView控件中如何获取所选行的设置的DataKeyNames值

本文详细介绍了如何在ASP.NET中利用GridView组件进行数据绑定,并通过设置DataKeyNames属性实现ID值的获取。同时展示了如何通过ID值进行后续操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.前台代码如下,DataKeyNames中设置为“ID”

<asp:GridView ID="gvListDoc" runat="server" CssClass="grid" AutoGenerateColumns="False"
                    DataKeyNames="ID" OnRowDataBound="gvListDoc_RowDataBound">
                    <Columns>
                        <asp:TemplateField>
                            <ItemStyle Width="40" HorizontalAlign="Center"></ItemStyle>
                            <HeaderTemplate>
                                <input type="checkbox" id="ckAll" onclick="allOrNot('gvListDoc', this.checked)">
                            </HeaderTemplate>
                            <ItemTemplate>
                                <asp:CheckBox ID="cbSel" runat="server"></asp:CheckBox>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:BoundField HeaderText="序号">
                            <ItemStyle HorizontalAlign="Center" Width="40"></ItemStyle>
                        </asp:BoundField>
                        <asp:BoundField HeaderText="编码" DataField="Code">
                            <ItemStyle Width="150" HorizontalAlign="Center"></ItemStyle>
                        </asp:BoundField>
                        <asp:BoundField HeaderText="标题" DataField="Name"></asp:BoundField>
                    </Columns>
                    <EmptyDataTemplate>
                        <div class="tip">
                            暂无记录!</div>
                    </EmptyDataTemplate>
</asp:GridView>

2.在进行数据绑定时,将获取的ID值赋给其属性

protected void gvListDoc_RowDataBound(object sender, GridViewRowEventArgs e)
   {
       if (e.Row.RowType == DataControlRowType.DataRow)
       {
           e.Row.Attributes["onmouseover"] = "this.style.backgroundColor='#ECFEDD'";
           e.Row.Attributes["onmouseout"] = "this.style.backgroundColor=''";
           e.Row.Cells[1].Text = (e.Row.RowIndex + 1).ToString();
           string id = this.gvListDoc.DataKeys[e.Row.RowIndex]["ID"].ToString();
           e.Row.Attributes.Add("ID", id);

          }

      }

3.前台获取ID属性

var dg = document.getElementById(gvListDoc);

var id=dg.rows[i].id;

进而可以用ID进行其他操作!

转载于:https://www.cnblogs.com/jiangdemin/archive/2011/12/28/2304876.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值