代码之家  ›  专栏  ›  技术社区  ›  user8512043

GridView中的特定标签值

  •  0
  • user8512043  · 技术社区  · 6 年前

    我正在尝试从中删除行 ASP.NET GridView 出于演示的目的,我正在尝试从行中检索名称。在 ItemTemplate GridView ,包括 Label 有身份证也有名字要显示。最后添加 Button 控制 GRIDVIEW 要删除特定行并尝试以下操作:

    <asp:GridView ID="grdData" runat="server" AutoGenerateColumns="false">
            <Columns>
                 <asp:TemplateField HeaderText="Id">
                    <ItemTemplate>
                        <asp:Label ID="lblId" runat="server" Text='<%# Eval("ProductId") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                  <asp:TemplateField>
                        <ItemTemplate>
                            <asp:Button ID="btnShow" runat="server" Text="Button" OnClick="btnShow_Click" />
                        </ItemTemplate>
                    </asp:TemplateField>
            </Columns>
    </asp:GridView>
    
    <asp:Label ID="lblMsg" runat="server"></asp:Label>
    

    在后面的代码中,我迭代了 GRIDVIEW 通过循环获取各个值,如下所示说出行的名称:

    protected void btnShow_Click(object sender, EventArgs e)
    {   
        foreach (GridViewRow row in grdData.Rows)
        {
            string val = ((Label)row.FindControl("lblName")).Text;
    
            lblMsg.Text = val;
        }
    }
    

    但不幸的是,每次我单击任何行按钮时都会得到姓氏,下面是我正在尝试的屏幕截图:

    ASP.NET GridView

    每当我单击任何按钮,它都会显示姓氏 冰淇淋 每一次。我错过了什么吗?

    0 回复  |  直到 6 年前
        1
  •  1
  •   Mike    6 年前
    <asp:GridView ID="grdData" runat="server" AutoGenerateColumns="false">
                <Columns>
                     <asp:TemplateField HeaderText="Id">
                        <ItemTemplate>
                            <asp:Label ID="lblId" runat="server" Text='<%# Eval("ProductId") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Name">
                        <ItemTemplate>
                            <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                      <asp:TemplateField>
                            <ItemTemplate>
                                <asp:Button ID="btnShow" runat="server" Text="Button" OnClick="btnShow_Click" CommandArgument='<%# Eval("Name") %>' />
                            </ItemTemplate>
                        </asp:TemplateField>
                </Columns>
        </asp:GridView>
    
        <asp:Label ID="lblMsg" runat="server"></asp:Label>
    
        protected void btnShow_Click(object sender, EventArgs e)
        {    
            lblMsg.Text = (sender as Button).CommandArgument;
        }