跟小D每日学口语

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

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进行其他操作!

posted on 2011-12-28 15:32  blankjoin  阅读(636)  评论(0编辑  收藏  举报

导航