WedTM
WedTM

Reputation: 2647

ASP.NET - programmatically generated delete button

I'm trying to create a simple button that deletes a row from the database. I would like to set the ID of the control to something like delete_MATERIALID_button however, when I do this:

<asp:Button ID='delete_<%# Eval("MatID") %>_button' runat="server" Text="Delete" />

I get an error that the name can't be generated like that.

I know that there must be a simple solution, I just can't figure it out.

Upvotes: 0

Views: 507

Answers (4)

cweston
cweston

Reputation: 11647

You can also add the command argument value in the repeater's OnItemDataBound event. In this event you have access to the data item, so it makes it very easy to pull the ID from the data item object, find the current delete button for the current row being bound, and apply the command argument to that control.

For example:

    protected void rptrExample_OnItemDataBound(object Sender, RepeaterItemEventArgs Args)
    {
        if (Args.Item.ItemType == ListItemType.Item || Args.Item.ItemType == ListItemType.AlternatingItem)
        {
            SomeBusinessObj Obj = (SomeBusinessObj)Args.Item.DataItem;

            Button btnDelete = (Button)Args.Item.FindControl("btnDelete");
            btnDelete.CommandArgument = Obj.ID;
        }
    }

Upvotes: 0

nitin dhiman
nitin dhiman

Reputation: 1

you can't do it like this, u need to specify a fix id there, and a command name(like delete) and u can pass that id in command argument... and on onCommand event you will get both of these values, command name and command argument...

niitn dhiman

Upvotes: 0

ScottE
ScottE

Reputation: 21630

The button would have to be named like so:

<asp:Button ID='<%# Eval("MatID", "delete_{0}_button") %>' runat="server" Text="Delete" />

But, as Shuwaiee has said, using the CommandArgument is probably a better place for the id.

CommandArgument='<%# Eval("MatID")%>'

Upvotes: 4

Shuwaiee
Shuwaiee

Reputation: 677

Why not save the ID in CommandArgument easier to deal with

Upvotes: 2

Related Questions