开发者

How to re-bind ListView on OnClick event of a button?

this seemed simple at first but I can't get it to work.

I have the following scenario:

        <asp:ListView ID="CommentsListView" runat="server">
            <LayoutTemplate>
                    <asp:PlaceHolder ID="itemPlaceholder" runat="server" />
            </LayoutTemplate>
            <ItemTemplate>
                <UC:Comment runat="server" CommentItem="<%# CurrentComment %>" />
                <br />
            </ItemTemplate>
        </asp:ListView>
        <asp:TextBox ID="NewComment" runat="server" />
        <asp:ImageButton ImageUrl="/images/ball.png" runa开发者_StackOverflow中文版t="server"
                      OnClick="SubmitComment" />

Code:

    protected void Page_Load(object sender, EventArgs e)
    {
         RenderListView();
    }

    protected void RenderListView()
    {
        CommentsListView.DataSource = //Get the data source objects
        CommentsListView.DataBind();
    }

    protected CommentObject CurrentComment
    {
        get { return (CommentObject)Page.GetDataItem(); }
    }

    protected void SubmitComment(object sender, ImageClickEventArgs e)
    {   
        //code to submit comment

        RenderListView();
    }

basically, when I submit a comment, I want to see it in the ListView, but I don't. "MyControl" gets a null comment in the post-back, for all of the items (not just the new one).

Only after I refresh the page, I can see the new comment that I'v submitted. I can't however refresh the page every submit because this code is inside an UpdatePanel (the issue occurs without the UpdatePanel as well).

Any idea how to solve this?


I can't find any specifics on this, but I have a hunch the user control in your ItemTemplate is causing the issue. Can you remove it and see if it works?


I notice that you are calling RenderListView in both SubmitComment and PageLoad which I believe will cause it to fire twice when the button is clicked (with PageLoad firing first). It looks like the code you posted is simplified. Is it possible that there is something happening in the PageLoad which is sabotaging your SubmitComment steps?


I finally solved it, if anyone else may encounter this -

The solution was to avoid "<%#" and instead use the ItemDataBound event:

 <asp:ListView ID="Comments" runat="server" 
OnItemDataBound="CommentsItemDataBound">

and the method itself:

protected void CommentsItemDataBound(object sender, ListViewItemEventArgs e)
{
    var commentItem = (Comment)(((ListViewDataItem)e.Item).DataItem);

    var commentControl = (Comment)e.Item.FindControl("CommentControl");
    commentControl.CommentItem = commentItem;
}

This way, the binding of each control works as expected.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜