0

I am generating buttons inside foreach loop

<% foreach (var myObject in myObjectList)
   {
%>
       <b>Text field</b>: <%= myObject.Text%><br>                     
       <asp:Button ID="" runat="server" OnClick="WaitQueueDeleteBtn_Click" CommandArgument="pass myObjectText" Text="Delete"/>

<% } %>

It seems that I cannot use myObject's field inside CommandArgument however myObjectList is accessible

i.e

<asp:Button ID="" runat="server" OnClick="WaitQueueDeleteBtn_Click" CommandArgument="<%#myObjectList.Count%>" Text="Delete"/>

The above statement would work but the one below would not

<asp:Button ID="" runat="server" OnClick="WaitQueueDeleteBtn_Click" CommandArgument="<%#myObject.Text %>" Text="Delete"/>

Any idea why? And how can I pass myObject's field values as CommandArgument?

Update:

Button method in class

protected void WaitQueueDeleteBtn_Click(object sender, EventArgs e)
{

}
8
  • how the method WaitQueueDeleteBtn_Click is defined Commented Jul 12, 2018 at 12:03
  • @un-lucky I have updated the question Commented Jul 12, 2018 at 12:05
  • what is myObject? will it have a property called Text? .Count is working means it may be abollection. could you please recheck Commented Jul 12, 2018 at 12:16
  • Possible duplicate of Aspx Web Forms Command argument Commented Jul 12, 2018 at 12:17
  • yes myObject has property called Text myObjectList is List of some class let's say Foo. So myObjectList is List<Foo> and myObject is Foo and Foo has property Text Commented Jul 12, 2018 at 12:18

1 Answer 1

1

It's so easy with Repeater

Markup

<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater1_ItemCommand">
    <ItemTemplate>
        <div><b>Text field</b>: <%# Eval("Text") %></div>
        <asp:Button runat="server" CommandArgument='<%# Eval("ID") %>' Text="Delete" />
    </ItemTemplate>
</asp:Repeater>

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        Repeater1.DataSource = YOUR_DATA_SOURCE; // myObjectList
        Repeater1.DataBind();

        // ...
    }
}

protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
    if (e.CommandArgument == null) return;

    var id = int.Parse(e.CommandArgument.ToString());

    // your logic here ...
}

You can add multiple buttons and using CommandName can figure out which one clicked.

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.