Repeater Loses it's data on PostBacks

2019-05-30 23:47发布

问题:

Repeater Markup:

<asp:Repeater ID="stat_Rptr" runat="server">
                <ItemTemplate>
                    <asp:CheckBox ID="IsSelected_ChkBx" runat="server" Text='<%# Eval("Item") %>' />
                    &nbsp;<asp:TextBox ID="Value_TxtBx" runat="server"></asp:TextBox>
                    <asp:HiddenField ID="ID_HdnFld" runat="server" Value='<%# Eval("ID") %>' />
                </ItemTemplate>
                <SeparatorTemplate>
                    <br></br>
                </SeparatorTemplate>
            </asp:Repeater>

Code-Behind:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            PopulateStatRptr();
        }
     }


    private void PopulateStatRptr()
    {
        SqlConnection conn;
        SqlCommand comm;
        SqlDataReader reader;

        string _connString = "Data Source=localhost\\SqlExpress;Initial Catalog=MyDb;Integrated Security=True";

        conn = new SqlConnection(ConString);
        comm = new SqlCommand("SELECT ID, Item FROM Stats", conn);

        try
        {
            conn.Open();
            reader = comm.ExecuteReader();
            stat_Rptr.DataSource = reader;
            stat_Rptr.DataBind();
            reader.Close();
        }

        finally
        {
            conn.Close();
        }
    }

回答1:

Ok, it seems that Repeater is a dynamic control. If you are binding in the codebehind you have to realize that the textbox and checkboxes in the itemtemplate do not exist until you DataBind(). If you disable viewstate, you won't see them unless you databind on every page load. You are getting your values from viewstate in this case.

Check this link out.



回答2:

Bind on Page_Init instead of Page_Load.



回答3:

Get rid of the if (!IsPostBack) code and call your function every time.