?
Solved

ListView in AJAX UpdatePanel not displaying newest data

Posted on 2010-03-23
5
Medium Priority
?
1,892 Views
Last Modified: 2013-11-07
I had this for another question, but I screwed up and posted some login cridentials by mistake. lets try this again. "Masterpass", please continue to help me again. anyone else, pelase step in. I am pulling my hair out.

Think of this in terms of a simple CHAT program. UpdatePanel 1 has the listview that displays the chat posts.  UpdatePanel 3 has the textbox and submit button to post the chat posts.

When I click the submit button, I execute the database insert 100% no prob. but the listview does not update itself to show the latest record inserted.

I have used the updatepanel1.update() call, and it will refresh the updatepanel, but not add the data to the listview.

I have tried the listview.databind() and it will refresh the listview, but it does a full refresh of the listview, which casues a reset of the div scroll bar and makes that listview flicker when changing, which I cant have.

I need it to simply show the new records posted in a normal ajax style without refreshing the entire thing and casueing un-needed bandwidth issues and user frustration with its flicker.

Thing that drives me crazy is that I have done this before and had it work as described. so Im not sure exactly what I am missing.. I did this along time ago and Im sure it wasnt anything complicated then.


=========

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="ChatApp.aspx.vb" Inherits="ChatApp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
   
      function pageLoad() {
      }
   
    </script>
   
    <script type="text/javascript" language="JavaScript">

        var cX = 0; var cY = 0; var rX = 0; var rY = 0;
        function UpdateCursorPosition(e) { cX = e.pageX; cY = e.pageY; }
        function UpdateCursorPositionDocAll(e) { cX = event.clientX; cY = event.clientY; }
        if (document.all) { document.onmousemove = UpdateCursorPositionDocAll; }
        else { document.onmousemove = UpdateCursorPosition; }
        function AssignPosition(d) {
            if (self.pageYOffset) {
                rX = self.pageXOffset;
                rY = self.pageYOffset;
            }
            else if (document.documentElement && document.documentElement.scrollTop) {
                rX = document.documentElement.scrollLeft;
                rY = document.documentElement.scrollTop;
            }
            else if (document.body) {
                rX = document.body.scrollLeft;
                rY = document.body.scrollTop;
            }
            if (document.all) {
                cX += rX;
                cY += rY;
            }
            d.style.left = (cX + 10) + "px";
            d.style.top = (cY + 10) + "px";
        }
        function HideContent(d) {
            if (d.length < 1) { return; }
            document.getElementById(d).style.display = "none";
        }
        function ShowContent(d) {
            if (d.length < 1) { return; }
            var dd = document.getElementById(d);
            AssignPosition(dd);
            dd.style.display = "block";
        }
        function ReverseContentDisplay(d) {
            if (d.length < 1) { return; }
            var dd = document.getElementById(d);
            AssignPosition(dd);
            if (dd.style.display == "none") { dd.style.display = "block"; }
            else { dd.style.display = "none"; }
        }
        //-->
</script>


    <link href="Styles/StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div style="display:none;">
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
    </div>
   
    <div class="SiteHeader">
    </div>
   
 
   
    <div class="SiteWrapper">
       
    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
      <Triggers>
     <asp:AsyncPostBackTrigger ControlID="Button1" />
      </Triggers>
     
    <ContentTemplate>
    <asp:Timer ID="Timer1" runat="server" Interval="5000"></asp:Timer>
        <div class="MainContent">
       
       
        <asp:ListView ID="ListView1" runat="server" DataKeyNames="post_id"
                DataSourceID="SqlDataSource1" EnableTheming="False"
                EnableModelValidation="True">
         
         <ItemTemplate>            
            <tr>
               <td>
               
               <table class="borderstyle">
               <tr>
               <td class="borderstyleTD">
                               
                                <table class="TableNothing">
                                <tr>
                                <td>
                               
                                <p class="borderstyleTDposttxt"><a onclick="ShowContent('uniquename<%# Eval("post_id") %>'); return true;" href="javascript:ShowContent('uniquename<%# Eval("post_id") %>')"><img alt="OPTIONS" class="imageLink" src="Images/plus.png" /></a> <b class="Username"><%# Eval("username") %>:</b>
                               
                                </td>
                                <td>
                               
                                <p style="text-align:right;">
                                     <img height="12" src="Images/GoldStar.png" />
                                     <img height="12" src="Images/GoldStar.png" />
                                     <img height="12" src="Images/GoldStar.png" />
                                     <img height="12" src="Images/SilverStar.png" />
                                     <img height="12" src="Images/SilverStar.png" />
                                </p>
                               
                                </td>
                                </tr>
                                </table>
                               
               <p class="borderstyleTDposttxt"><%# Eval("post") %></p>
               <p class="borderstyleTDpostdate">
                   <img src="Images/buddy.png" height="16" /> <%# Eval("post_date","{0:g}")  %></p>
                          <div id="uniquename<%# Eval("post_id") %>" class="hoverDIV">
                                <div align="right">
                                <%# Eval("username") %> - <a onclick="HideContent('uniquename<%# Eval("post_id") %>'); return true;" href="javascript:HideContent('uniquename<%# Eval("post_id") %>')">
                                    <img border="0" height="12" title="CLOSE" src="Images/red-x.png" /></a>
                                </div>    
                                <div align="center">
                                <asp:ImageButton ToolTip="EDIT" ID="EditButton" runat="server" CommandArgument='<%# Eval("post_id") %>' OnClick="EditButtonClickHandler" CausesValidation="False" ImageUrl="Images/edit.png" />
                                <asp:ImageButton ToolTip="DELETE" ID="DeleteButton" runat="server" CommandArgument='<%# Eval("post_id") %>' OnClick="DeleteButtonClickHandler" CausesValidation="False" ImageUrl="Images/delete.png" />
                                <asp:ImageButton ToolTip="WARN" ID="WarnButton" runat="server" CommandArgument='<%# Eval("post_id") %>' OnClick="WarnButtonClickHandler" CausesValidation="False" ImageUrl="Images/warn.png" />
                                <asp:ImageButton ToolTip="SUSPEND" ID="SuspendButton" runat="server" CommandArgument='<%# Eval("post_id") %>' OnClick="SuspendButtonClickHandler" CausesValidation="False" ImageUrl="Images/suspend.png" />
                                <asp:ImageButton ToolTip="BAN" ID="BanButton" runat="server" CommandArgument='<%# Eval("post_id") %>' OnClick="BanButtonClickHandler" CausesValidation="False" ImageUrl="Images/ban-BIG.png" />
                                </div>
                          </div>  
               </td>
               </tr>
               </table>
               
               
               <table class="SepRow">
               <tr>
               <td></td>
               </tr>
               </table>
                                     
               </td>
            </tr>          
        </ItemTemplate>
       
     
               
                <EmptyDataTemplate>
                    <table runat="server" style="background-color: #FFFFFF;border-collapse: collapse;border-color: #999999;border-style:none;border-width:1px;">
                        <tr>
                            <td>No data was returned.</td>
                        </tr>
                    </table>
                </EmptyDataTemplate>

                 <LayoutTemplate>
            <table id="Table2" runat="server" class="PostTable" cellpadding="0" cellspacing="0">
                <tr id="Tr1" runat="server">
                    <td id="Td1" runat="server">
                   
                        <table width="100%" ID="itemPlaceholderContainer" runat="server" border="0" cellspacing="0" cellpadding="0" style="border-collapse: collapse;border-color: #999999;border-style:none;border-width:1px;font-family: Verdana, Arial, Helvetica, sans-serif;">
                            <tr ID="itemPlaceholder" runat="server">
                            </tr>
                        </table>
                    </td>
                </tr>
                <tr id="Tr3" runat="server">
                    <td id="Td2" runat="server" style="text-align: center;background-color: #333333;font-family: Verdana, Arial, Helvetica, sans-serif;color: #000000;">
                        <asp:DataPager ID="DataPager1" runat="server" PageSize="25">
                            <Fields>
                                <asp:NextPreviousPagerField ButtonType="link" ShowFirstPageButton="True"
                                    ShowNextPageButton="False" ShowPreviousPageButton="False" />
                                <asp:NumericPagerField />
                                <asp:NextPreviousPagerField ButtonType="link" ShowLastPageButton="True"
                                    ShowNextPageButton="False" ShowPreviousPageButton="False" />
                            </Fields>
                       </asp:DataPager>
                   </td>
                </tr>
            </table>
        </LayoutTemplate>
               
            </asp:ListView>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server"
                ConnectionString="<%$ ConnectionStrings:braapchatConnectionString %>"
                SelectCommand="SELECT TOP(50) * FROM post ORDER BY post_id DESC">
            </asp:SqlDataSource>
       
        </div>
       
    </ContentTemplate>
    </asp:UpdatePanel>
       
        <div class="MainContentRightAdsWrapper">
           
           
            <asp:UpdatePanel ID="UpdatePanel2" runat="server">
                   
            <ContentTemplate>
           
           <div class="RightAds">
           
            <asp:Panel ID="EditPanel" runat="server" Visible="false" EnableViewState="False">
               <asp:TextBox CssClass="PostTXTbox" ID="EditBox" runat="server" EnableViewState="False" Width="328px" MaxLength="201"></asp:TextBox>
               <asp:Button ID="EditButton" runat="server" Text="Edit" EnableViewState="False" />
               
            </asp:Panel>
           
             
             <asp:Panel ID="DeletePanel" runat="server" Visible="false" EnableViewState="False">
               <asp:TextBox CssClass="PostTXTbox" ID="DeleteBox" runat="server" EnableViewState="False" Width="328px" MaxLength="201"></asp:TextBox>
               <asp:Button ID="DeleteButton" runat="server" Text="Delete" EnableViewState="False" />
               
            </asp:Panel>
               
           
            </div>
           
            </ContentTemplate>
            </asp:UpdatePanel>
       
        </div>
   
    </div>
   
 
   
    <asp:UpdatePanel ID="UpdatePanel3" runat="server" UpdateMode="Conditional">

    <ContentTemplate>
   
   <div class="SiteFooter">
   
      <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="Images/refresh.png"
            CausesValidation="False" EnableViewState="False" ToolTip="REFRESH" />  
        <asp:TextBox CssClass="PostTXTbox" ID="PostBox" runat="server" EnableViewState="False" Width="328px" MaxLength="201"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="POST" EnableViewState="False" />
   
        <asp:Button ID="Button2" runat="server" Text="addit" CausesValidation="False" />
       
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
            ControlToValidate="PostBox" Display="None"
            ErrorMessage="You need to enter some text" SetFocusOnError="True"></asp:RequiredFieldValidator>
        <asp:RegularExpressionValidator ValidationExpression='^(.|\n){0,200}$' ControlToValidate="PostBox" ID="RegularExpressionValidator1" runat="server" ErrorMessage="your text is too long."></asp:RegularExpressionValidator>
         
         <asp:regularexpressionvalidator id="noSinQuo" controltovalidate="PostBox"
            validationexpression='^[,\.\!\#\:a-zA-Z0-9\040]+$' ErrorMessage="Your post contains text that is not allowed. Please remove any '&' symbols, single and/or double quotes or special characters such as '=' , '+' , '/' , '\'"
            Runat="server" Display="None" EnableTheming="True"
            ToolTip="Fix Error"/>
        <asp:RegularExpressionValidator Display="None" ControlToValidate="PostBox" ValidationExpression='^((?!fuck|FUCK|Fuck|FuCk|fUcK|fuCK|FUck|fUCk|fUCK|fucK|f u c k|F U C K|shit|pussy|dick|fag|gay|homo|cunt|cock).)*$' ID="RegularExpressionValidator2" runat="server" ErrorMessage="No bad language"></asp:RegularExpressionValidator>

    <asp:ValidationSummary ID="ValidationSummary1" runat="server"
            ShowMessageBox="True" ShowSummary="False" />
   
    </div>
   
    </ContentTemplate>
    </asp:UpdatePanel>
   
   
    </form>
</body>
</html>



========================  THE CODE BEHIND FILE ==============================



Partial Class ChatApp
    Inherits System.Web.UI.Page

    'Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
    '    ListView1.ItemCommand = New EventHandler < ListViewCommandEventArgs > (ListView1_ItemCommand)
    'End Sub

    Protected Sub ButtonClickHandler(ByVal sender As [Object], ByVal e As EventArgs)

        Dim btn As ImageButton
        btn = DirectCast(sender, ImageButton)
        If btn IsNot Nothing Then
            Dim recordId As String = btn.CommandArgument
            'Do what ever you want with the recordID now

            PostBox.Text = recordId
            ' Label1.Text = recordId
            ' Panel1.Visible = True
            EditPanel.Visible = True
            EditBox.Text = "Post text to edit"

        End If

        'PostBox.Text = "button4 EDIT"
        'Label1.Text = "button 4 edit"
    End Sub


    'This is the code that is executed when you click the edit post link in the popup options.
    Protected Sub EditButtonClickHandler(ByVal sender As [Object], ByVal e As EventArgs)

        Dim btn As ImageButton
        btn = DirectCast(sender, ImageButton)
        If btn IsNot Nothing Then
            Dim recordId As String = btn.CommandArgument
            'Do what ever you want with the recordID now

            PostBox.Text = recordId
            ' Label1.Text = recordId
            ' Panel1.Visible = True
            EditPanel.Visible = True
            EditBox.Text = "Post text to edit" & " " & recordId

        End If

        'PostBox.Text = "button4 EDIT"
        'Label1.Text = "button 4 edit"
    End Sub


    'This is the code that is executed when you click the DELETE post link in the popup options.
    Protected Sub DeleteButtonClickHandler(ByVal sender As [Object], ByVal e As EventArgs)

        Dim btn As ImageButton
        btn = DirectCast(sender, ImageButton)
        If btn IsNot Nothing Then
            Dim recordId As String = btn.CommandArgument
            'Do what ever you want with the recordID now

            PostBox.Text = recordId
            ' Label1.Text = recordId
            ' Panel1.Visible = True
            DeletePanel.Visible = True
            DeleteBox.Text = "Post to DELETE" & " " & recordId

        End If

        'PostBox.Text = "button4 EDIT"
        'Label1.Text = "button 4 edit"
    End Sub




    'This is the code that is executed when you click the WARN post link in the popup options.
    Protected Sub WarnButtonClickHandler(ByVal sender As [Object], ByVal e As EventArgs)

        Dim btn As ImageButton
        btn = DirectCast(sender, ImageButton)
        If btn IsNot Nothing Then
            Dim recordId As String = btn.CommandArgument
            'Do what ever you want with the recordID now

            PostBox.Text = recordId
            ' Label1.Text = recordId
            ' Panel1.Visible = True
            EditPanel.Visible = True
            EditBox.Text = "Post text to WARN" & " " & recordId

        End If

        'PostBox.Text = "button4 EDIT"
        'Label1.Text = "button 4 edit"
    End Sub




    'This is the code that is executed when you click the SUSPEND post link in the popup options.
    Protected Sub SuspendButtonClickHandler(ByVal sender As [Object], ByVal e As EventArgs)

        Dim btn As ImageButton
        btn = DirectCast(sender, ImageButton)
        If btn IsNot Nothing Then
            Dim recordId As String = btn.CommandArgument
            'Do what ever you want with the recordID now

            PostBox.Text = recordId
            ' Label1.Text = recordId
            ' Panel1.Visible = True
            EditPanel.Visible = True
            EditBox.Text = "Post text to SUSPEND" & " " & recordId

        End If

        'PostBox.Text = "button4 EDIT"
        'Label1.Text = "button 4 edit"
    End Sub




    'This is the code that is executed when you click the BAN post link in the popup options.
    Protected Sub BanButtonClickHandler(ByVal sender As [Object], ByVal e As EventArgs)

        Dim btn As ImageButton
        btn = DirectCast(sender, ImageButton)
        If btn IsNot Nothing Then
            Dim recordId As String = btn.CommandArgument
            'Do what ever you want with the recordID now

            PostBox.Text = recordId
            ' Label1.Text = recordId
            ' Panel1.Visible = True
            EditPanel.Visible = True
            EditBox.Text = "Post text to BAN" & " " & recordId

        End If

        'PostBox.Text = "button4 EDIT"
        'Label1.Text = "button 4 edit"
    End Sub



    Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
        PostBox.Text = "button ADDIT"
    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim SQLStr As String
        Dim ConnString As String


        ConnString = ConfigurationManager.ConnectionStrings("braapchatConnectionString").ConnectionString

        SQLStr = "INSERT into post(user_id, room_id, username, post) VALUES(1,1,'test_name','" & PostBox.Text & "')"

        Dim SQLConn As New Data.SqlClient.SqlConnection() 'The SQL Connection
        Dim SQLCmd As New Data.SqlClient.SqlCommand() 'The SQL Command

        SQLConn.ConnectionString = ConnString 'Set the Connection String
        SQLConn.Open() 'Open the connection

        SQLCmd.Connection = SQLConn 'Sets the Connection to use with the SQL Command
        SQLCmd.CommandText = SQLStr 'Sets the SQL String
        SQLCmd.ExecuteNonQuery() 'Executes SQL Commands Non-Querys only

        SQLConn.Close() 'Close the connection

        PostBox.Text = "inserted: " & PostBox.Text
        UpdatePanel1.Update()


    End Sub


End Class

0
Comment
Question by:godeep
  • 3
4 Comments
 
LVL 1

Author Comment

by:godeep
ID: 28390777
anyone?
0
 
LVL 11

Accepted Solution

by:
G0ggy earned 2000 total points
ID: 28433553
You've posted a lot and don't have time to debug your code, especially without your database. I have got this working locally, although it's clumsy and I would not go live with it. I've tested this with a friends browser and we were able to message each other.

Hope this helps you.
HTML:

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    
    <asp:Timer ID="Timer1" Interval="2000" Enabled="true" runat="server"></asp:Timer>
    
    <div>
        <asp:UpdatePanel ID="upMessage" UpdateMode="Conditional" runat="server">
            <ContentTemplate>
                <asp:TextBox ID="txtMessage" Width="500px" runat="server"></asp:TextBox>
                <br />
                <asp:Button ID="btnAddMessage" Text="Post Message" runat="server" />
            </ContentTemplate>
        </asp:UpdatePanel>
        
        <asp:UpdatePanel ID="upMessageList" UpdateMode="Conditional" runat="server">
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
            </Triggers>
            
            <ContentTemplate>
                <asp:ListBox ID="lbMessageList" Rows="20" Width="500px" runat="server"></asp:ListBox>
            </ContentTemplate>
        </asp:UpdatePanel>

Code Behind:

Public connString As String = ConnectionStrings("chatConn").ConnectionString

    Protected Sub btnAddMessage_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddMessage.Click
        Dim objConn As New SqlConnection(connString)
        Dim cmd As New SqlCommand("usp_AddMessage", objConn)
        cmd.CommandType = CommandType.StoredProcedure

        cmd.Parameters.Add(New SqlParameter("@messageText", SqlDbType.NChar, 75))
        cmd.Parameters("@messageText").Value = txtMessage.Text
        cmd.Parameters("@messageText").Direction = ParameterDirection.Input

        objConn.Open()
        cmd.ExecuteNonQuery()

        objConn.Close()
        objConn.Dispose()
        cmd.Dispose()
    End Sub

    Protected Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Dim objConn As New SqlConnection(connString)
        Dim cmd As New SqlCommand("usp_GetMessages", objConn)
        cmd.CommandType = CommandType.StoredProcedure

        Dim dt As New DataTable()
        Dim da As New SqlDataAdapter
        da.SelectCommand = cmd

        da.Fill(dt)

        lbMessageList.Items.Clear()

        For Each row As DataRow In dt.Rows
            lbMessageList.Items.Add(New ListItem(row("messageText").ToString))

        Next

        objConn.Close()
        objConn.Dispose()
        cmd.Dispose()
        da.Dispose()
    End Sub

Get Mesages SP:

PROCEDURE usp_GetMessages
	-- Add the parameters for the stored procedure here
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	select MessageText from dbo.msg order by MessageID desc
END

Add Message SP:

PROCEDURE usp_AddMessage
	-- Add the parameters for the stored procedure here
	@messageText nchar(75)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

    -- Insert statements for procedure here
	insert into dbo.msg (MessageText) values (@messageText)
END

Open in new window

0
 
LVL 1

Author Comment

by:godeep
ID: 28450468
right back at you. :)  ... That is a totally new concept  there. I will try it out and see how it works. thanks..
0
 
LVL 1

Author Comment

by:godeep
ID: 30462830
I had to put this project on hold for a bit. I have yet to test your concept yet. hopefully soon.
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
There may be issues when you are trying to access Outlook or send & receive emails or due to Outlook crash which leads to corrupt or damaged PST file. To eliminate the corruption from your PST file, you need to repair the corrupt Outlook PST file. U…
In this video I will demonstrate how to set up Nine, which I now consider the best alternative email app to Touchdown.
Suggested Courses

592 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question