Matt Roberts
Matt Roberts

Reputation: 26897

Why is my repeater control empty on postback?

I think this is a "doh" moment caused by me not having dome WebForms dev for a few years..

I have a repeater which which contains a bunch of checkboxes:

<asp:Repeater EnableViewState="true" ID="IDTypesRepeater" runat="server" OnItemDataBound="IdTypesRepeaterItemDataBound">
                        <HeaderTemplate/>
                        <ItemTemplate>
                            <asp:CheckBox EnableViewState="true" ID="chkIdType" Text="<%# ((KeyValuePair<string,int>)Container.DataItem).Key %>" runat="server" />
                            <asp:HiddenField ID="idType" Value="<%# ((KeyValuePair<string,int>)Container.DataItem).Value %>" runat="server"/>
                            <br />
                        </ItemTemplate>
                        </asp:Repeater>

I need to get the checkboxes that are selected in the code behind:

 foreach (RepeaterItem repeaterItem in IDTypesRepeater.Items)
        {
            if ( ((CheckBox)repeaterItem.FindControl("chkIdType")).Checked )
            {
                // Do something
            }
        }

But on postback, this code isn't working! I know about always databinding a repeater, so I've done this:

protected void Page_Load(object sender, EventArgs e)
{
    IDTypesRepeater.DataSource = DocTemplateHelper.GetApplicableIDTypes().Where(type => type.Value != 0);
    IDTypesRepeater.DataBind();
}

So this repopulates the repeater, but the Update code never finds any checked checkboxes.. Any ideas?

Upvotes: 3

Views: 9631

Answers (3)

Junaid
Junaid

Reputation: 1755

This should fix it. You are binding the control on postback hence losing the values. You can bind it after handling any event to show the updated record.

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
      IDTypesRepeater.DataSource = DocTemplateHelper.GetApplicableIDTypes().Where(type => type.Value != 0);
      IDTypesRepeater.DataBind();
    }
}

Upvotes: 0

TheGeekYouNeed
TheGeekYouNeed

Reputation: 7539

Bind in the Page_Init event

protected void Page_Init(object sender, EventArgs e)
{
    IDTypesRepeater.DataSource = DocTemplateHelper.GetApplicableIDTypes().Where(type => type.Value != 0);
    IDTypesRepeater.DataBind();
}

Upvotes: 5

4b0
4b0

Reputation: 22323

Be sure to use the !Page.IsPostBack method in your pageload. Otherwise, the Repeater will keep getting reset, and all your checkboxes will be in there default value (unchecked)

Upvotes: 3

Related Questions