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

asked on

Troubles with focus() HELP

Hello Experts:

I've been getting help with setting focus on a textbox inside my editable datagrid.  Here is the paq'd question where I was helped:
Focus help
https://www.experts-exchange.com/questions/20816773/ASP-Net-Editable-datagrid-the-focus-command-HELP.html

It was working fine when we finished up this question.  I then got help on keeping the scrollback position on the datagrid here:

Anchor help
https://www.experts-exchange.com/questions/20823426/Retaining-scroll-position-on-asp-net-datagrid.html

This worked fine as it kept its scroll position after postback.

Then I realized that with both codes in the focus stopped working.  I hadn't changed the code at all for focus().  I need help getting this to work again.  If I remove the scrollback code the focus works again fine.
I've now even changed my datagrid from a boundcolumn for the focus to a template column like most of the examples suggest.

Currently my code for focus looks like this:
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 = DataGrid1.Items(e.Item.ItemIndex).Cells(6).FindControl("CommentBox")
         'scriptJs = "<script language=javascript>" & vbCrLf
         'scriptJs &= "document.getElementById('" & CommentBox.UniqueID & "').focus();" & vbCrLf
         'scriptJs &= "document.getElementById('" & CommentBox.UniqueID & "').select();" & vbCrLf
         'scriptJs &= "alert('Textbox focus')" & vbCrLf
         'scriptJs &= "<" & "/script>"
         'If (Not Me.IsStartupScriptRegistered("Startup")) Then
      '      Me.RegisterStartupScript("Startup", scriptJs)
        ' End If
       CommentBox = DataGrid1.Items(e.Item.ItemIndex).Cells(0).FindControl("CommentBox")
       RegisterStartupScript("focus", "<Script language=""JavaScript"">" & vbCrLf & _
       vbTab & "Form1." & CommentBox.ClientID & ".focus();" & _
       vbCrLf & vbTab & "Form1." & CommentBox.ClientID & ".select();"& _
       vbCrLf & "<" & "/script>")
               End Sub

You can still see the old code I was using from the help I was getting in the link above.  The new code functions the same as the old does.  Using UniqueID the select() is working but the focus() is not.  Using ClientID neither work.

The code I use for scrollback is 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.UniqueID)
      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)
            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

This is how my datagrid looks now:
<form runat="server" id="Form1">
          <asp:datagrid id="DataGrid1" runat="server"  Font-Size="10pt" ShowFooter="True" AutoGenerateColumns="False" width="90%" CellSpacing="2" GridLines="None" HorizontalAlign="Center" CellPadding="3" BackColor="White" ForeColor="Black" OnPageIndexChanged="DataGrid_Page" PageSize="25" 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>
            <EditItemStyle Width="100%" BackColor="Cyan"></EditItemStyle>
            <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:TemplateColumn HeaderText="Comments">
                <ItemTemplate>
                <%# DataBinder.Eval(Container.DataItem, "CommentBox") %>
                </ItemTemplate>
                <EditItemTemplate>
                        <asp:TextBox id="CommentBox" runat="server" width="95%" Text='<%# DataBinder.Eval(Container.DataItem, "CommentBox") %>' />
                        </EditItemTemplate>
                        </asp:TemplateColumn>
                        <asp:EditCommandColumn ButtonType="LinkButton" UpdateText="Update" CancelText="Cancel" EditText="Edit" ItemStyle-Font-Size="smaller" ItemStyle-Width="7%"></asp:EditCommandColumn>
                        
            </Columns>
        </asp:datagrid>
        <br />
        <br />
        <asp:Label id="Message" runat="server" width="80%" forecolor="red" enableviewstate="false"></asp:Label>
    </form>

So the scrollback code works fine like it is here.  Doesn't matter if I use ClientID or UniqueID in this case.  There is one line that I changed from the help I was given here.  This: e.Item.Cells(7).Controls.Add(anchor) used to be this: e.Item.Cells(0).Controls.Add(anchor).  
I changed it because if I leave it at 0 it cuts out the first column in my datagrid.  I'm assuming it should point to the editcolumn?  My editcolumn is on the right side of the grid instead of the traditional left.  So its cell would be 7.

At this point I've given up.  I've worked through almost all online examples and still get the same results each time.  Is it impossible to mix the two here?  I need to be done with this so I can move on to some other changes so any help is appreciated!

Avatar of TwoSide
TwoSide

In your web page properties try to  Set SmartNavigation = True(It's a suggestion probably not an answer!)

TwoSide
Avatar of jay-are

ASKER

Yeah I tried SmartNavigation at first and its not even remotely accurate after postback.  That's why I was trying to use a script to keep scroll position.

Thanks for the suggestion!
Would be curious to see how the JavaScript block renders...  Would you do a 'Show Source" from the browser, paste and send back.  I do something very similar and have had no problems using the .clientid property.


Dim HTMLid As String = DataGrid1.Items(e.Item.ItemIndex).Cells(5).FindControl("ddlOption").ClientID()

Dim scriptsJs as string
scriptJs = "<script language=javascript>" & vbCrLf
scriptJs &= "document.getElementById('" & HTMLid & "').focus();" & vbCrLf
scriptJs &= "document.getElementById('" & CommentBox.UniqueID & "').select();" & vbCrLf
scriptJs &= "</script>"


Hope this helps,

Dante :)...
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, no need to worry about the delay!  I know you are busy.  I changed the code like you posted and I keep getting this erros:

Compiler Error Message: BC30390: 'System.Web.UI.Page.Private Sub RegisterScriptBlock(key As String, script As String, ByRef scriptBlocks As System.Collections.IDictionary)' is not accessible in this context because it is 'Private'.

Source Error:

 

Line 233:            jScript.Append("<" & "/script>")
Line 234:            
Line 235:            Me.RegisterScriptBlock("Bookmark", jScript.ToString())
Line 236:      End Sub
Line 237:</script>
 

Source File: c:\inetpub\wwwroot\ASPX\New\testgrid.aspx    Line: 235
Avatar of jay-are

ASKER

Oops, didn't read your post very well

Changed Me.RegisterScriptBlock
to
Me.RegisterStartupScript

now I'm having another error:

Exception Details: System.InvalidCastException: Specified cast is not valid.

Source Error:


Line 79:        BindGrid()
Line 80:                                      
Line 81:   commentBox = CType(DataGrid1.Items(DataGrid1.EditItemIndex).Cells(7).Controls(0), TextBox)
Line 82:                                             
Line 83:   scriptJs = "<script language=javascript>" & vbCrLf
 

Source File: c:\inetpub\wwwroot\ASPX\New\testgrid.aspx    Line: 81

This is probably from all the changes I've been making.  I've got everything back the way it was but I'm still having this error.
Avatar of jay-are

ASKER

Ok I'm not sure why but these declarations for commentbox work:

inside the Edit sub I used:
Dim scriptJs As String
Dim commentBox As Textbox
                                             DataGrid1.EditItemIndex = e.Item.ItemIndex
BindGrid()
                              
CommentBox = DataGrid1.Items(e.Item.ItemIndex).Cells(6).Controls(0)
                                            
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

This is working!  Thank you so much.  I've been struggling with this since last week!  haha
I know you are busy with your project and I appreciate you taking time to check in on me  :)
Glad to help, jay-are. Good luck to you project too.

Regards
x_com