1

I've been trying to send a parameter to onclick func. Look at my code, there is a foreach there. This is for creating <li> related database. This Item coming from database. I want to use it again in delete buttons onclick. It must be come from on buttons <li>'s anchor. Or it could be from foreach i dont know. Problem: i dont know how i can send that string(Item) to my onclick function.

<div id="depListId" class="panel"> <ul id="depUl" class="list-group" runat="server"> <% foreach (var Item in dep) { %> <li class="list-group-item"><a><%= Item %></a><asp:Button runat="server" class="deleteButton" CommandArgument='<%# Eval(??HERE??)%>' OnCommand="delete_button" Text="Delete" /></li> <% } %> </ul> </div>

2 Answers2

1

You could use a repeater control for this:

.ASPX:

<div id="depListId" class="panel">
    <ul id="depUl" class="list-group" runat="server">
        <asp:Repeater ID="Repeater1" runat="server">
            <ItemTemplate>
                <li class="list-group-item">
                    <a><%# Container.DataItem.ToString() %></a>
                    <asp:Button runat="server" class="deleteButton" 
                        CommandArgument='<%# Container.DataItem.ToString() %>' 
                        OnCommand="delete_button" 
                        Text="Delete" />
                </li>
            </ItemTemplate>
        </asp:Repeater>
    </ul>
</div>

Code behind:

public List<string> dep { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        dep = new List<string> { "Item 1", "Item 2", "Item 3" };
        Repeater1.DataSource = dep;
        Repeater1.DataBind();
    }
}

protected void delete_button(object sender, CommandEventArgs e)
{
    string text = e.CommandArgument.ToString();
}
Denys Wessels
  • 16,829
  • 14
  • 80
  • 120
  • This is perfectly working. (Sorry for this late feedback) Thank u Mr. Wessels. –  Aug 01 '16 at 05:17
0

the 1st argument in your server onclick method is the button control (object sender), so cast it to your button and aks for its attributes https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclick(v=vs.110).aspx

bresleveloper
  • 5,940
  • 3
  • 33
  • 47
  • I still dont know how to get that anchors text. –  Jul 29 '16 at 14:35
  • try looking at `((Button)Sender).Attributes` – bresleveloper Jul 29 '16 at 14:38
  • I cant figured out it. It's been a day im looking that. (Also i tryed attributes this morning) Look at my code. There is eval in there. I think if i can send the Item with that, it will be great –  Jul 29 '16 at 14:57