[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 672
  • Last Modified:

ASP.NET Repeater Control & Array Index

I have a working repeater control filled by an array. I have added a delete button, but am unsure how to reference the array index in the Command Argument to pass to the delete command.

<asp:Repeater ID="gvRC" runat="server">
  ...
 <ItemTemplate>
      <li><%#Container.DataItem %>&nbsp;<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/images/icon_delete.gif" CommandName="deleteStation"  CommandArgument=" "  /></li>
 ...
</asp:Repeater>

The repeater is filled with a simple array by:
gvRC.DataSource = aryRC
gvRC.DataBind()

0
el_scotty
Asked:
el_scotty
1 Solution
 
wht1986Commented:
The index of the item is already included in the RepeaterCommandEventArgs argument of the ItemCommand event.

My code behind example is included below.  e.Item.ItemIndex contains the index of the item clicked.
 private List<string> DataSource
    {
        get
        {
            if (ViewState["DATASOURCE"] == null)
                this.DataSource = new List<string>(new string[] { "Hello", "World", "Good Bye", "Sanity" });
            return (List<string>)ViewState["DATASOURCE"];
        }
        set
        {
            ViewState["DATASOURCE"] = value;
        }
    }
 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            this.Repeater1.DataSource = DataSource;
            this.Repeater1.DataBind();
        }
    }
 
    protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName.Equals("deleteStation"))
        {
            this.DataSource.RemoveAt(e.Item.ItemIndex);
            this.Repeater1.DataSource = DataSource;
            this.Repeater1.DataBind();
        }
    }

Open in new window

0
 
el_scottyAuthor Commented:
Perfect, Thank You. I figured it must be something simple like that.
0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now