Search code examples
c#asp.netaspx-user-control

How do I bind two elements into a single Link Button ASP.NET


I am trying to bind two elements from a list to a Link Button. The following works separately on two link buttons:

<asp:LinkButton ID="LinkButton2" ForeColor="Black" runat="server" Text='<%# Bind("Name") %>'></asp:LinkButton>

<asp:LinkButton ID="LinkButton1" ForeColor="Black" runat="server" Text='<%# Bind("UserID") %>' OnClick="LinkButton1_Click"></asp:LinkButton>

I want to do it so on the Text Attribute it holds both Name and UserID Bind.

For example;

<asp:LinkButton ID="LinkButton1" ForeColor="Black" runat="server" Text='<%# Bind("UserID") % + " " + <%# Bind("Name") %>' OnClick="LinkButton1_Click"></asp:LinkButton>

How Can I achieve this?


Solution

  • You can do this. Bind comma separated values in CommandArgument property of LinkButton:

    CommandArgument='<%#Eval("Name") + ";" + Eval("UserID") %>'
    

    then on click:

    protected void LinkButton1_Click(object sender, System.EventArgs e)
    {
     LinkButton lnkButton = (LinkButton)sender;
     string[] args = lnkButton.CommandArgument.Split(';');
    
     string name = string.Empty, userId = string.Empty;
     if (args.Length == 2)
     {
       name = args[0];
       userId = args[1];
     }
    }