Solved

Retaining scroll position on asp.net datagrid

Posted on 2003-12-11
16
4,013 Views
Last Modified: 2013-11-25
Hello experts!

I'm new to programming and I'm having trouble making this work with my datagrid.  I've looked at examples at Asp Alliance, dotnetjunkies, and devhood.  I can't get any of them to work.  

I've tried SmartNavigation but it never returns to the right position...always a few records down or up depending on its mood.

I'm currently messing with the example from dotnetjunkies.  I need some help with it cause I'm not sure I'm doing any of this right.
http://www.dotnetjunkies.com/Article/E474B0FC-20D2-48B3-93B5-DC4CB3C4A1AB.dcik

there's the link to the article

I think I have the code in the right place, but of course I'm new to this so probably not.  Here is my code:

<script language="javascript">
<!--
      function __doPostBack(eventTarget, eventArgument) {
            var theform = document.ctrl0;
            theform.__EVENTTARGET.value = eventTarget;
            theform.__EVENTARGUMENT.value = eventArgument;
            theform.submit();
      }
// -->
</script>

<html>
<head>
</head>
<body style="FONT-FAMILY: arial">
    <h4>C.I.T. - 1020 &nbsp;&nbsp;&nbsp;<%=Now %>
    </h4>
    <hr size="2" />
<form runat="server" id="Form1" method="post" enableviewstate="true">
 <asp:label id="whatever" runat="server" />
       <input type="hidden" name="__eventtarget" value="" />
       <input type="hidden" name="__eventargument" value="" />      

          <a name="#Update"></a>
       
 <asp:datagrid id="DataGrid1" runat="server" enableviewstate="true" SmartNavigation="true" Font-Size="10pt" ShowFooter="True" OnItemDataBound="ComputeSum" AutoGenerateColumns="False" width="90%" CellSpacing="2" GridLines="None" HorizontalAlign="Center" CellPadding="3" BackColor="White" ForeColor="Black" OnPageIndexChanged="DataGrid_Page" PageSize="40" AllowPaging="true" OnCancelCommand="DataGrid_Cancel" OnUpdateCommand="DataGrid_Update" OnEditCommand="DataGrid_Edit" OnItemCommand="DataGrid_ItemCommand" DataKeyField="Control#">
            <HeaderStyle font-bold="True" forecolor="white" backcolor="#4A3C8C"></HeaderStyle>
            <PagerStyle horizontalalign="Right" backcolor="#C6C3C6" mode="NumericPages" font-size="smaller"></PagerStyle>
            <ItemStyle backcolor="#DEDFDE"></ItemStyle>
            <FooterStyle backcolor="#C6C3C6"></FooterStyle>
           
            <Columns>
                <asp:BoundColumn DataField="Control#" ReadOnly="False" HeaderText="Cust. Number" />
                <asp:BoundColumn DataField="Customer Last Name" ReadOnly="True" HeaderText="Name" />
                <asp:HyperLinkColumn DataTextField="Reference#" HeaderText="Deal #" datanavigateurlfield="Reference#" datanavigateurlformatstring="dealno.aspx?Reference={0}" navigateurl="dealno.aspx" target="_blank" />
                <asp:BoundColumn DataField="Bank Name" ReadOnly="True" HeaderText="Bank Name" />
                <asp:BoundColumn DataField="SumAmt" DataFormatString="{0:c}" ReadOnly="True" HeaderText="Amount" />
                <asp:BoundColumn DataField="daysold" ReadOnly="True" HeaderText="Days Old" />
                <asp:BoundColumn DataField="CommentBox" HeaderText="Comments" ReadOnly="False" />
      <asp:EditCommandColumn ButtonType="LinkButton" UpdateText="Update" CancelText="Cancel" EditText="Edit" ItemStyle-Font-Size="smaller" ItemStyle-Width="7%"></asp:EditCommandColumn>
                        
            </Columns>
        </asp:datagrid>
     <asp:Label id="Message" runat="server" width="80%" forecolor="red" enableviewstate="false"></asp:Label>
    <input type=hidden id=pagex name=pagex value=0 runat=server>
      <input type=hidden id=pagey name=pagey value=0 runat=server>  
    </form>
   
</body>
</html>
</script>
<script runat="server">
location.href="#<%=Request.Form["__EVENTTARGET"]%>";                              
</script>

As it is right now I get this error:

Compiler Error Message: BC30188: Declaration expected.

Source Error:

 

Line 274:</script>
Line 275:<script runat="server">
Line 276:      location.href="#<%=Request.Form["__EVENTTARGET"]%>";                              
Line 277:</script>

 

Source File: c:\inetpub\wwwroot\ASPX\New\datagrid1020.aspx    Line: 276

Any ideas?   Should I try using a different example?
Help!

0
Comment
Question by:jay-are
  • 7
  • 5
  • 2
  • +2
16 Comments
 
LVL 10

Expert Comment

by:GoodJun
Comment Utility
0
 

Author Comment

by:jay-are
Comment Utility
GoodJun:

I've been all through that guide for various things and it never mentions retaining scroll position unless I've overlooked that part.

Can you tell me which part out of the 15 have that?
0
 
LVL 12

Expert Comment

by:roverm
Comment Utility
Maybe you can use this:
http://www.metabuilders.com/Tools/ScrollingPanel.aspx

D'Mzz!
RoverM
0
 
LVL 29

Expert Comment

by:David H.H.Lee
Comment Utility
jay-are ,
Here's my solutions when i need to bookmark my aspx file - Datagrid control.

bookmark.aspx
-----------------------
<script runat="server" language="vb">

    Public bookmarkIndex As Integer = 0 ' The index of the bookmarked row
    Public bookMark As Boolean = True 'Controls is bookmarked

    Sub DataGrid_ItemDataBound(ByVal sender As Object, ByVal e As DataGridItemEventArgs)
        If (bookMark) Then

            Dim anchor As New LiteralControl

            anchor.Text = "<a name=""#" + e.Item.ClientID + """>"
            e.Item.Cells(0).Controls.Add(anchor)
        End If
    End Sub

    Sub DataGrid_ItemCommand(ByVal source As Object, ByVal e As DataGridCommandEventArgs)
        If (bookMark) Then
            bookmarkIndex = e.Item.ItemIndex
            Me.InsertScriptBlock(e.Item.ClientID)
        End if
    End Sub

    Sub InsertScriptBlock(ByVal strItem As String)
        Dim jScript As New System.Text.StringBuilder
        jScript.Append("<script language=""JavaScript"">")
        jScript.Append("location.href=""#")
        jScript.Append(strItem)
        jScript.Append(""";")
        jScript.Append("</script>")

        Me.RegisterClientScriptBlock("Bookmark", jScript.ToString())
    End Sub

</script>

<html>
<head>
</head>
<body style="FONT-FAMILY: arial">
   <h4>C.I.T. - 1020 &nbsp;&nbsp;&nbsp;<%=Now %>
   </h4>
   <hr size="2" />
<form runat="server" id="Form1" method="post" enableviewstate="true">
<asp:label id="whatever" runat="server" />
<asp:datagrid id="DataGrid1" runat="server" enableviewstate="true" SmartNavigation="true" Font-Size="10pt" ShowFooter="True" OnItemDataBound="ComputeSum" AutoGenerateColumns="False" width="90%" CellSpacing="2" GridLines="None" HorizontalAlign="Center" CellPadding="3" BackColor="White" ForeColor="Black" OnPageIndexChanged="DataGrid_Page" PageSize="40" AllowPaging="true" OnCancelCommand="DataGrid_Cancel" OnUpdateCommand="DataGrid_Update" OnEditCommand="DataGrid_Edit" OnItemCommand="DataGrid_ItemCommand"
OnItemDataBound="DataGrid_ItemDataBound"
DataKeyField="Control#">
           <HeaderStyle font-bold="True" forecolor="white" backcolor="#4A3C8C"></HeaderStyle>
           <PagerStyle horizontalalign="Right" backcolor="#C6C3C6" mode="NumericPages" font-size="smaller"></PagerStyle>
           <ItemStyle backcolor="#DEDFDE"></ItemStyle>
           <FooterStyle backcolor="#C6C3C6"></FooterStyle>
         
            <Columns>
               <asp:BoundColumn DataField="Control#" ReadOnly="False" HeaderText="Cust. Number" />
               <asp:BoundColumn DataField="Customer Last Name" ReadOnly="True" HeaderText="Name" />
               <asp:HyperLinkColumn DataTextField="Reference#" HeaderText="Deal #" datanavigateurlfield="Reference#" datanavigateurlformatstring="dealno.aspx?Reference={0}" navigateurl="dealno.aspx" target="_blank" />
               <asp:BoundColumn DataField="Bank Name" ReadOnly="True" HeaderText="Bank Name" />
               <asp:BoundColumn DataField="SumAmt" DataFormatString="{0:c}" ReadOnly="True" HeaderText="Amount" />
               <asp:BoundColumn DataField="daysold" ReadOnly="True" HeaderText="Days Old" />
               <asp:BoundColumn DataField="CommentBox" HeaderText="Comments" ReadOnly="False" />
    <asp:EditCommandColumn ButtonType="LinkButton" UpdateText="Update" CancelText="Cancel" EditText="Edit" ItemStyle-Font-Size="smaller" ItemStyle-Width="7%"></asp:EditCommandColumn>
                   
           </Columns>
       </asp:datagrid>
    <asp:Label id="Message" runat="server" width="80%" forecolor="red" enableviewstate="false"></asp:Label>
   <input type=hidden id=pagex name=pagex value=0 runat=server>
     <input type=hidden id=pagey name=pagey value=0 runat=server>  
   </form>
</body>
</html>

Regards
x_com
0
 
LVL 12

Expert Comment

by:roverm
Comment Utility
x_com: BRILIANT!
0
 

Author Comment

by:jay-are
Comment Utility
X_com

I keep getting an error on this line:

jScript.Append("</script>")

Double quote expected?

Going off the other examples I have I changed it to:
jScript.Append("<" & "/script>")

The grid loads fine but doesn't retain scroll position after I update.  That's the position I specifically want to capture.  After a user hits update I want it to stay on that line.  

I'm going to have to rename my datagrid to "x_comDataGrid"!  :)
As always I appreciate your help.
0
 

Author Comment

by:jay-are
Comment Utility
I see one thing I missed in your code:
OnItemDataBound="DataGrid_ItemDataBound"

I have this attribute already for:
OnItemDataBound="ComputeSum"

How can I do both?
0
 

Author Comment

by:jay-are
Comment Utility
So once I remove the ComputeSum it works perfectly.  
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 29

Accepted Solution

by:
David H.H.Lee earned 500 total points
Comment Utility
Thanks for your compliment, roverm :-)

jay-are ,
Put my code inside your existing sub routine (ComputeSum):

Sub ComputeSum(ByVal sender As Object, ByVal e As DataGridItemEventArgs)
      'Keep your existing code

      'add my code
      If (bookMark) Then

           Dim anchor As New LiteralControl

           anchor.Text = "<a name=""#" + e.Item.ClientID + """>"
           e.Item.Cells(0).Controls.Add(anchor)
       End If
End Sub

Afterward, all will work as you thought. I'll try my best to help (if got a better chance) :-)

Regards
x_com
0
 
LVL 8

Expert Comment

by:nishikanth
Comment Utility
0
 

Author Comment

by:jay-are
Comment Utility
x_com

That did it!  Thanks!  
0
 
LVL 29

Expert Comment

by:David H.H.Lee
Comment Utility
Glad to help, jay-are

Regards
x_com
0
 

Author Comment

by:jay-are
Comment Utility
x_com

I just noticed something strange.  After adding the new code to my datagrid I suddenly lose the focus() on my textbox when the user hits edit.  The select() is still working, as it highlights text in the CommentBox, but you can no long just start typing without using the mouse and clicking on the CommentBox.  

I went back to a different datagrid that just had the focus and no scrollback code and its working fine.  So I rem'd out the focus code and added in the scrollback code and it the scrollback code works fine.

Why can't I mix the two?  It may be something I did with your code.  I altered it a little.
 anchor.Text = "<a name=""#" + e.Item.ClientID + """>"
was changed to
 anchor.Text = "<a name=""#" + e.Item.UniqueID + """>"

Just like we did for the focus and select code in a previous question.  Otherwise it wouldn't work.

So if I have both the focus and scrollback code together it works assuming I've used UniqueID for the anchor.text:
Scrollback is working, keeps position on page after update
Select() works in CommentBox, highlights the text in the box when user hits edit
Focus() isn't working when user hits edit.

Now If I use ClientID in the anchor.text then:
Scrollback isn't working
Select() still works fine
Focus() now works fine


Ideas?

I'll post my code so you can see if there's something stupid(most likely) I've done here. :)

Sub DataGrid_ItemCommand(ByVal Source As Object, ByVal E As DataGridCommandEventArgs)
   
                        ' this event fires prior to all of the other commands
                        ' use it to provide a more graceful transition out of edit mode
   
                        'CheckIsEditing(e.CommandName)
               If(bookMark) Then
                        bookmarkIndex = e.Item.ItemIndex
                        Me.InsertScriptBlock(e.Item.ClientID)
                       End If
               End Sub

 Sub DataGrid_Edit(Sender As Object, E As DataGridCommandEventArgs)
   
                        ' turn on editing for the selected row
   
                                                        
                              Dim scriptJs As String
                              Dim commentBox As Textbox
                     DataGrid1.EditItemIndex = e.Item.ItemIndex
                     BindGrid()
                                                
                    CommentBox = CType(DataGrid1.Items(DataGrid1.EditItemIndex).Cells(6).Controls(0), TextBox)
                    scriptJs = "<script language=javascript>" & vbCrLf
                    scriptJs &= "document.getElementById('" & CommentBox.UniqueID & "').focus();" & vbCrLf
                    scriptJs &= "document.getElementById('" & CommentBox.UniqueID & "').select();" & vbCrLf
                    scriptJs &= "<" & "/script>"
                    If (Not Me.IsStartupScriptRegistered("Startup")) Then
                    Me.RegisterStartupScript("Startup", scriptJs)
                    End If
                End Sub

Sub DataGrid_ItemDataBound(ByVal sender As Object, ByVal e As DataGridItemEventArgs)
            If(bookMark) Then
                  Dim anchor As New LiteralControl
                  
                  anchor.Text = "<a name=""#" + e.Item.UniqueID + """>"
                  e.Item.Cells(7).Controls.Add(anchor)
                  If e.Item.ItemType = ListItemType.Item OR _
                  e.Item.ItemType = ListItemType.AlternatingItem then
                              
                  Dim viewCount as Integer = _
                  Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "SumAmt"))
                  viewCountSum += viewCount
                  ElseIf e.Item.ItemType = ListItemType.Footer then
                  e.Item.Cells(4).Text = "Page Total: " & String.Format("{0:c}", viewCountSum)
                  End If
            End If
      End Sub
      
      Sub InsertScriptBlock(ByVal strItem As String)
            Dim jScript As New System.Text.StringBuilder
            jScript.Append("<script language=""JavaScript"">")
            jScript.Append("location.href=""#")
            jScript.Append(strItem)
            jScript.Append(""";")
            jScript.Append("<" & "/script>")
            
            Me.RegisterClientScriptBlock("Bookmark", jScript.ToString())
      End Sub

Thanks for helping!!
0
 
LVL 29

Expert Comment

by:David H.H.Lee
Comment Utility
jay-are,
if you want to use ClientID ,change to this format (or if you want to use UniqueID, change it with same method - vice versa):
  Me.InsertScriptBlock(e.Item.ClientID)

..
anchor.Text = "<a name=""#" + e.Item.ClientID + """>"

It seem work well for me. What browser you're using?
try this (add a comments line):
                   scriptJs = "<script language=javascript>" & vbCrLf
                   scriptJs &= "document.getElementById('" & CommentBox.UniqueID & "').focus();" & vbCrLf
                   scriptJs &= "document.getElementById('" & CommentBox.UniqueID & "').select();" & vbCrLf
                   scriptJs &= "alert('Cursor focus on Edit Textbox automatically')" & vbCrLf '<----check comment
                   scriptJs &= "<" & "/script>"

Regards
x_com
0
 

Author Comment

by:jay-are
Comment Utility
Well when I change the anchor code to Unique ID it continues to work but the focus() code isn't working.
It seems to be focusing on something just not the CommentBox.  When I click Update I can hit tab once and I'm in the CommentBox and can begin typing.  

I changed the ID around on both sets of code and it didn't make a difference.  The scrollback continues to work just like it should but I don't receive focus on the CommentBox.  I added in your comment line.  When you click edit an alert pops up saying "cursor focus on...etc." and you hit "ok" and then you can start typing in the commentbox.  This of course isn't what I need since the managers will find that annoying each time they want to update.  

One thing that I noticed during my testing that is strange is this:
Sub DataGrid_ItemDataBound(ByVal sender As Object, ByVal e As DataGridItemEventArgs)
            If(bookMark) Then
            Dim anchor As New LiteralControl
            anchor.Text = "<a name=""#" + e.Item.UniqueID + """>"
            e.Item.Cells(7).Controls.Add(anchor)
            End If
      End Sub

e.Item.Cells(7).Controls.Add(anchor)

Do I have to use a specific cell for the anchor?  You had yours originallly set to 0.  When I used 0 it would make my first column in my datagrid dissappear.  So I changed it to 7 which is just outside of what I use(I use 0-6).
I'm guessing this isn't a big deal since the anchor is working fine.


Still I'm more worried about the focus() working as it adds a lot of ease to updating the datagrid for the users.  If this becomes a problem I can change the grid to only show like 5 records and then the scrollback won't be needed.  I'd rather have the functionality of both though.  Help!  :)

BTW:  All users have IE 6 or above.  No netscape users or anything funny like that.  All windows XP sp1.


0
 
LVL 29

Expert Comment

by:David H.H.Lee
Comment Utility
jay-are,
sorry for my delay. I had reply the answer to your latest thread(http://oldlook.experts-exchange.com/Programming/Programming_Languages/Dot_Net/Q_20830596.html). Sorry again for my delay..

Regards
x_com
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

763 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now