Link to home
Start Free TrialLog in
Avatar of jay-are
jay-areFlag for United States of America

asked on

Retaining scroll position on asp.net datagrid

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!

Avatar of GoodJun
GoodJun

Avatar of jay-are

ASKER

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?
Maybe you can use this:
http://www.metabuilders.com/Tools/ScrollingPanel.aspx

D'Mzz!
RoverM
Avatar of David H.H.Lee
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
x_com: BRILIANT!
Avatar of jay-are

ASKER

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.
Avatar of jay-are

ASKER

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?
Avatar of jay-are

ASKER

So once I remove the ComputeSum it works perfectly.  
ASKER CERTIFIED SOLUTION
Avatar of David H.H.Lee
David H.H.Lee
Flag of Malaysia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jay-are

ASKER

x_com

That did it!  Thanks!  
Glad to help, jay-are

Regards
x_com
Avatar of jay-are

ASKER

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!!
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
Avatar of jay-are

ASKER

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.


jay-are,
sorry for my delay. I had reply the answer to your latest thread(http://oldlook.experts-exchange.com/questions/20830596/Troubles-with-focus-HELP.html). Sorry again for my delay..

Regards
x_com