Repeater Loses it's data on PostBacks

2019-05-30 23:51发布

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();
        }
    }

3条回答
我想做一个坏孩纸
2楼-- · 2019-05-31 00:34

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

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-05-31 00:38

Bind on Page_Init instead of Page_Load.

查看更多
一纸荒年 Trace。
4楼-- · 2019-05-31 00:42

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.

查看更多
登录 后发表回答