Solved

setting the focus on a row within a datagrid on a webform

Posted on 2004-04-06
18
907 Views
Last Modified: 2008-02-01
I am trying to set the focus to a certain row within a datagrid upon a selection made from a user this is how it is set up the user selects a sub heading from a drop down box and the focus gets set to the corresponding row on the datagrid. the problem is the row gets changed to textboxes is there any way around this.  my code is below.

 Select Case ddlAccount.SelectedItem.Value
            Case "1"
                numhold = "89"
            Case "2"
                numhold = "124"
            Case "3"
                numhold = "134"
            Case "4"
                numhold = "144"
            Case "5"
                numhold = "155"
            Case "6"
                numhold = "161"
            Case "7"
                numhold = "165"
            Case "8"
                numhold = "184"
            Case "9"
                numhold = "190"
            Case "10"
                numhold = "200"
            Case "11"
                numhold = "203"
            Case "12"
                numhold = "210"
end select


 if you look at the "dim focusBox as textbox" thats how the focus gets set to the row i dont want that because the row gets turned into textboxes. is there a better way to set the focus without changing the row?  


  Dim Dataset11 As New DataSet
        Dim scriptJs As String
        Dim objDataAdapter1 As New OleDbDataAdapter("SELECT * FROM [accounts$]", strConn)
        objDataAdapter1.Fill(Dataset11) 'dataadapter method
        dgAccounts.DataSource = Dataset11.Tables(0).DefaultView
        Dim index As Integer
        index = numhold
        dgAccounts.EditItemIndex = index

        dgAccounts.DataBind()
        Dim focusBox As TextBox
        focusBox = dgAccounts.Items(index).Cells(0).Controls(0)

        scriptJs = "<Script Language=JavaScript>" & vbCrLf
        scriptJs &= "document.getElementById('" & focusBox.UniqueID & "').focus();" & vbCrLf
        scriptJs &= "document.getElementById('" & focusBox.UniqueID & "').select();" & vbCrLf

        scriptJs &= "<" & "/script>"
        If (Not Me.IsStartupScriptRegistered("Startup")) Then
            Me.RegisterStartupScript("Startup", scriptJs)
        End If
0
Comment
Question by:tentavarious
  • 9
  • 4
  • 2
  • +2
18 Comments
 
LVL 10

Expert Comment

by:EBatista
ID: 10771370
not sure if i understand your Q, anyway, look at this link
http://aspnet.4guysfromrolla.com/articles/090902-1.aspx

0
 
LVL 10

Expert Comment

by:EBatista
ID: 10771372
are you saying that you dont want the textboxs to be rendered?
0
 
LVL 28

Expert Comment

by:mmarinov
ID: 10772432
Hi tentavarious,

Actually when you use
dgAccounts.EditItemIndex = index
dgAccounts.DataBind()

you tell to DataGrid that for this Item with Index inde, datagrid should use the controls in the EditTemplate
i don't understand what is the purpose of setting focus on row in the datagrid - but actually you can add additional column , with a hidden field in it
then when you want to set focus on the row - just set the focus to this hidden field


HTH
B..M
0
 

Author Comment

by:tentavarious
ID: 10774380
The purpose of setting the focus is because the datagrid has around 400 rows and is split into subsections that i gave up top they are in a dropdownlist and instead of having the user scrolling through the whole grid, i want to give the user the option of jumping to a specific spot within the grid by selecting the subheading from the dropdownlist.  The only way i have found how to do this is by setting the focus on a row, and the only way i now how to set the focus is within a text box so the row gets converted to textboxes so the focus can be set and i dont like doing it that way.  The hidden field sounds promising how would i go about doing that.  Would the whole column be invisible?  could you elborate?
0
 
LVL 28

Expert Comment

by:mmarinov
ID: 10774537
no
you have to set the visible/invisible state of the column manual
but you can insert the hidden field in one of other columns
example
<Columns>
  <asp:TemplateColumn>
    <ItemTemplate>
        <asp:TextBox id="YourTextBOx" runat="server" /> <!-- This is some of your controls that you are currently use-->
        <input type="hidden" id="someid">
    </ItemTemplate>
  </asp:TemplateColumn>
</Columns>


B..M
0
 

Author Comment

by:tentavarious
ID: 10774630
But how can i set the focus to the text box if its invisible?  Also how would i compare it to the case select i have at the top?
0
 
LVL 28

Expert Comment

by:mmarinov
ID: 10774934
NO, you won't set focus to INVISIBLE TextBox
you can use this
 Dim focusField As HtmlInputHidden
        focusField = dgAccounts.Items(index).Cells(0).FindCOntrol("someid")

        scriptJs = "<Script Language=JavaScript>" & vbCrLf
        scriptJs &= "document.getElementById('" & focusField .UniqueID & "').focus();" & vbCrLf

<Columns>
  <asp:TemplateColumn>
    <ItemTemplate>
        <asp:TextBox id="YourTextBOx" runat="server" /> <!-- This is some of your controls that you are currently use-->
        <input type="hidden" id="someid" runat="server" name="somename">
    </ItemTemplate>
  </asp:TemplateColumn>
</Columns>

B..M
0
 

Author Comment

by:tentavarious
ID: 10775137
Doesn't work i get an error saying can't move focus because it's invisible, not enabled or type that does not accept focus.  Is there anyotherway to jump to a row within a datagrid?  Or is the only way to set the focus?
0
 
LVL 28

Expert Comment

by:mmarinov
ID: 10775196
look here
http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/Q_20943480.html

may be the problem is that in my suggestion id and name attributes are different, but may be they should be the same
B..M
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:tentavarious
ID: 10775469
i call the method from the drop down event
 setfocus("hiddenfocus")

I added the template column
<input type="hidden" name="hiddenfocus" />

now how can i set the focus to the row that gets selected from the drop down, the numhold variable is equal to the row number on the datagrid. any ideas? i think this is the right way to do it.
 Sub setfocus(ByVal ctrl As String)
        'Please remember JavaScript objects are case sensitive
        Dim sJava As String = "<script language='Javascript'>document.Form1." & ctrl & ".focus(); </script>"
        RegisterStartupScript("setfocus", sJava)
    End Sub

0
 

Author Comment

by:tentavarious
ID: 10776148
i tried changing the setfocus sub procedure, but i cant get it to work i get a subscript out of range.  How can i get "ctrl" to equal the row number so the focus will get set to the correct row?

 Sub setfocus(ByVal ctrl As String)

        Dim index As Integer
        index = numhold
        ctrl = dgAccounts.Items(index).Cells(0).Controls(0).ToString
        Dim sJava As String = "<script language='Javascript'>document.Form1." & ctrl & ".focus(); </script>"
        RegisterStartupScript("setfocus", sJava)
    End Sub
0
 
LVL 28

Expert Comment

by:iboutchkine
ID: 10776775
numhold may be greater than the row count. In this case you will get Subscript out of range
0
 

Author Comment

by:tentavarious
ID: 10776925
How can i fix this? The number of rows goes past 300 and the highest value numhold could be is 240, numhold is a variable that gets set to a row number depending on what the user selects from the drop down.  What i need is for the focus to be set to the row number that is equal to the numhold, how can i change my above code to make it work?
0
 
LVL 28

Expert Comment

by:iboutchkine
ID: 10777123
make sure that the quantity of row is less than numhold
try
   focusField = dgAccounts.Items(index).Cells(0).FindCOntrol("someid")
catch
   msgbox("Sh........t")
End try
0
 

Author Comment

by:tentavarious
ID: 10777275
I dont know if that will work i have changed the sub procedure to

 Sub setfocus(ByVal ctrl As HtmlInputHidden)
Dim index As Integer
        Dim Dataset11 As New DataSet
        Dim objDataAdapter1 As New OleDbDataAdapter("SELECT * FROM [accounts$]", strConn)
        objDataAdapter1.Fill(Dataset11) 'dataadapter method
        dgAccounts.DataSource = Dataset11.Tables(0).DefaultView
        index = numhold
        dgAccounts.EditItemIndex = index
        dgAccounts.DataBind()

        ctrl = dgAccounts.Items(index).Cells(0).Controls(0)
        Dim sJava As String = "<script language='Javascript'>document.Form1." & ctrl.UniqueID & ".focus(); </script>"
        RegisterStartupScript("setfocus", sJava)
end sub

I dont have a focusField variable i am trying to set the focus to a template column i created within my datagrid dgAccounts. the focus should be set to the same row number as selected from the dropdownlist. I call the sub procedure
setfocus from the dropdownlist event and pass the "hiddenfocus" argument. I get an error on this line of code
"  ctrl = dgAccounts.Items(index).Cells(0).Controls(0)" I know i am not doing something right, but i can't figure out what.

<asp:datagrid id="dgAccounts" runat="server">
<Columns
      <asp:TemplateColumn>
      <ItemTemplate>                                                            <input type="hidden" name="hiddenfocus" />                                          </ItemTemplate>                                                      </asp:TemplateColumn>
</Columns>
</asp:datagrid>
0
 

Author Comment

by:tentavarious
ID: 10777471
Ok i changed it up and i got this error
The cast is not valid, before i had the focusbox as a textbox but then it converted the rows to textboxes which i dont want is there any control that i can set the focusbox to. that will not convert the rows and still be able to recieve the focus.
 Dim focusBox As HtmlInputHidden
Line 160:        focusBox = dgAccounts.Items(index).Cells(0).Controls(0)
Line 161:

Here is my code
  Dim Dataset11 As New DataSet
        Dim scriptJs As String
        Dim objDataAdapter1 As New OleDbDataAdapter("SELECT * FROM [accounts$]", strConn)
        objDataAdapter1.Fill(Dataset11) 'dataadapter method
        dgAccounts.DataSource = Dataset11.Tables(0).DefaultView
        Dim index As Integer
        index = numhold
        dgAccounts.EditItemIndex = index

        dgAccounts.DataBind()
        Dim focusBox As HtmlInputHidden
        focusBox = dgAccounts.Items(index).Cells(0).Controls(0)

        scriptJs = "<Script Language=JavaScript>" & vbCrLf
        scriptJs &= "document.getElementById('" & focusBox.UniqueID & "').focus();" & vbCrLf
        scriptJs &= "document.getElementById('" & focusBox.UniqueID & "').select();" & vbCrLf
        scriptJs &= "<" & "/script>"
        If (Not Me.IsStartupScriptRegistered("Startup")) Then
            Me.RegisterStartupScript("Startup", scriptJs)
        End If
0
 

Author Comment

by:tentavarious
ID: 10778506
i solved it, i just changed all my textbox properties to fit the rest of the datagrid and it blends in prettygood.

focusBox.ReadOnly = True
        focusBox.ForeColor = Color.DarkSlateBlue
        focusBox.Font.Size = Medium
        focusBox.BorderStyle = Groove

thanks for all of the help
0
 
LVL 7

Accepted Solution

by:
dante469 earned 500 total points
ID: 10778565
tentavarious.

Sorry so late to jump in but certain this is what you are looking for :)...

What I do is
1) Generate dummy data...  Certainly replace this w/ your data access
2) populate the ddl with unique entries from Col1...  You would replace with the column that contains the sections...
3) Put an anchor template column in the DG to set focus later
4) Generate jScript to jump to correct anchor based on DDL...

Recommend creating a new webform and code behind to see illustration then incorporate your REAL page....

Have Fun,
dante

BTW... Not against bonus points :)...


--- .aspx --->

<body>
            <form id="Form1" method="post" runat="server">
                  <asp:DropDownList id="ddl1" runat="server" AutoPostBack="True"></asp:DropDownList>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</P>
                  <asp:DataGrid id="dg1" runat="server">
                        <Columns>
                              <asp:TemplateColumn>
                                    <ItemTemplate>
                                          <a id="anchor" runat="server"></a>
                                    </ItemTemplate>
                              </asp:TemplateColumn>
                        </Columns>
                  </asp:DataGrid>
                  <a id="aTag" name="aTag" runat="server"></a>
            </form>
      </body>


--- Codebehind--->
    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        If Not IsPostBack Then
            Dim ds As New DataSet
            ds = datagen()

            Dim ddlSource As New ListItemCollection
            ddlSource = buildDDL(ds.Tables(0), "Col1")
            ddl1.DataSource = ddlSource
            ddl1.DataTextField = "Text"
            ddl1.DataValueField = "Value"
            ddl1.DataBind()

            dg1.DataSource = ds.Tables(0)
            dg1.DataBind()
        End If

    End Sub
    Function buildDDL(ByVal dt As DataTable, ByVal sColName As String) As ListItemCollection
        Dim LastVal As String
        Dim li As ListItem
        Dim lic As New ListItemCollection
        Dim dr As DataRow

        Dim iRowIndex As Integer = 0
        For Each dr In dt.Select("", sColName)   'Select sorted by Col1
            If LastVal Is Nothing OrElse Not ValEqual(LastVal, dr(sColName)) Then
                LastVal = dr(sColName)
                li = New ListItem
                li.Text = dr(sColName)
                li.Value = iRowIndex.ToString
                lic.Add(li)
            End If
            iRowIndex += 1
        Next
        Return lic
    End Function
    Private Function ValEqual(ByVal A As Object, ByVal B As Object) As Boolean
        '
        ' Compares two values to determine if they are equal. Also compares DBNULL.Value.

        If A Is DBNull.Value And B Is DBNull.Value Then Return True ' Both are DBNull.Value.
        If A Is DBNull.Value Or B Is DBNull.Value Then Return False ' Only one is DBNull.Value.
        Return A = B                                                ' Value type standard comparison
    End Function
    Function datagen() As DataSet
        Dim dt As New DataTable
        Dim dr As DataRow

        dt.Columns.Add(New DataColumn("col1", GetType(String)))
        dt.Columns.Add(New DataColumn("col2", GetType(String)))
        dt.Columns.Add(New DataColumn("col3", GetType(String)))


        Dim i As Integer
        Dim i1 As Integer
        Dim iDTE As DateTime = "1/15/2004"
        Dim iTDTE As DateTime


        For i1 = 1 To 5
            For i = 1 To 10
                dr = dt.NewRow()
                dr(0) = "FromDDL" & i1.ToString("##")
                dr(1) = "col2" & i.ToString("##")
                dr(2) = "col3" & i.ToString("##")
                dt.Rows.Add(dr)
            Next
        Next

        Dim ds As New DataSet
        ds.Tables.Add(dt)

        Return ds

    End Function
    Private Sub ddl1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ddl1.SelectedIndexChanged
        'Change the FOCUS of the dg to the anchor based on change in DDL
        Dim focusField As Object
        focusField = dg1.Items(ddl1.SelectedItem.Value).Cells(0).FindControl("anchor")

        Dim sString As System.Text.StringBuilder
        sString = New System.Text.StringBuilder
        sString.Append("<script language='Javascript'>")
        sString.Append("location.href='#")
        sString.Append(focusField.ClientID)
        sString.Append("';")
        sString.Append("</")
        sString.Append("script>")

        If (Not Me.IsStartupScriptRegistered("Startup")) Then
            Me.RegisterStartupScript("Startup", sString.ToString)
        End If
    End Sub
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

Normally the drop down box control found in the .Net framework tools is able to select just one data and value at a time, which is displayed on the text area.   But what if you want to have multiple values to be selected in the drop down box? As …
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…
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.
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

744 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

13 Experts available now in Live!

Get 1:1 Help Now