Search code examples
c#buttonlabelcommandargument

How to extract label text at button click


So what I want to do is to extract the text from a label when a button is clicked. What I've got so far is the following:

    <asp:Label ID="lbl_carID" runat="server" Text="Label"></asp:Label>
    <asp:Label ID="lbl_ownerID" runat="server" Text="Label"></asp:Label>

    <asp:Button ID="btn_wishList" runat="server" Text="Add to wish list"  CssClass="btn" CommandArgument='<%= lbl_carID.Text.ToString() %>' OnCommand="btn_wishList_Command" />
    <asp:Button ID="btn_offer" runat="server" Text="Make Offer" CssClass="btn" CommandArgument='<%= lbl_ownerID.Text.ToString() %>' OnCommand="btn_offer_Command" />

I have also tried without the ToString() method, but it is not working. Also tried without the = after %. I am new to code insertion, so I guess it is something really small, but I cannot make it work. Any suggestions ?

EDIT: This is the code behind btn_offer_command. Both commands are identical at start, so I am posting the shorter code.

protected void btn_offer_Command(object sender, CommandEventArgs e)
    {
        string id = (string)e.CommandArgument;
        Session["ownerToBeOffered"] = id;
        Response.Redirect("LoggedInFeatures/MakeOffer.aspx");
    }

Solution

  • I believe you cannot use <%= %> inside properties with a runat="server".

    Try to pass the CommandName and check it in your handler.

    Example

    <asp:Label ID="lbl_carID" runat="server" Text="Labeddl1"></asp:Label>
    <asp:Label ID="lbl_ownerID" runat="server" Text="Label1"></asp:Label>
    
    <asp:Button CommandName="carID" CssClass="btn" ID="btn_wishList" OnCommand="btn_wishList_Command" runat="server" Text="Add to wish list" />
    <asp:Button  CommandName="ownerID" CssClass="btn" ID="btn_offer" runat="server" Text="Make Offer" OnCommand="btn_offer_Command" />
    

    And in your Code try something like the following...

        protected void btn_wishList_Command(object sender, CommandEventArgs e)
    {
        if (e.CommandName == "carID")
        {
            //Do Something here
        }
    }
    
    protected void btn_offer_Command(object sender, CommandEventArgs e)
    {
        if (e.CommandName == "ownerID")
        {
            //Do Something here
        }
    }