Scroll to matching word in datagrid

logicsolutions
logicsolutions used Ask the Experts™
on
Hi Experts,

I found the following code whilst searching the EE forums. It seems like it's going to do the job I need.

You can see the thread here: http://www.experts-exchange.com/Programming/Languages/Scripting/JScript/Q_23739257.html?sfQueryTermInfo=1+scroll+search+texbox

Basically what I need is the facility to type a letter in a text box and the datagrid will automatically scroll to that line.

Example. If I type 'EF' in the text box it will search the second column Item Number and take you to the first value it find which begins with EF.

The code used in the EE forum was:

// ==

function createlettermap()
{
 var txtsearchbox = document.getElementById("txtHeaderSearch");
    var tbl = txtsearchbox.parentNode.parentNode.parentNode.parentNode;
    var rows = tbl.rows;
    var j = 0;  
    count = 0;
    var searchChar = rows[1].cells[1].firstChild.nodeValue.toLowerCase().charAt(0); // assign first char of first row
    for(var i=1;i< rows.length;i++)
    {
        if (rows[i].cells[1].firstChild.nodeValue.toLowerCase().charAt(0)!= searchChar) // if the first char of current row is not equal to previous row
        {
        //create an array entry for that character  for ex: rows starts with "A" starts at 1 and ends at 10, the entry would be listmap{[a,1,20]}
            listmap[j] = new Array();
            listmap[j][0] = searchChar;
            listmap[j][1] = i - count;
            listmap[j][2] = i-1;
            j++;                  

            searchChar = rows[i].cells[1].firstChild.nodeValue.toLowerCase().charAt(0); //re set search char to current row first character
            count = 1  ;
        }
        else
            count++;
    }
}

//

I don't know if the above code is of any use but hopefully it's just a matter of plugging it in.

How can I add an input text box which will look similar to the picture below on my page and have it perform the function of autoscrolling to the inputed text.

I have attached my existing code and have no idea where everything should go.

Big Thanks Experts.
<%@ Page Language="C#" EnableViewState="true" %>
<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Data.Odbc" %>
 
 
<script runat="server">
 
    void Page_Load(object sender, EventArgs e) {
        if(!Page.IsPostBack)
        {
            // TODO: Update the ConnectionString and CommandText values for your application
            string ConnectionString = @"DSN=MYOB;uid=Username;pwd=Password";
            string CommandText = "select Items.ItemNumber, Items.ItemName, Items.TaxInclusiveLastPurchasePrice FROM Items ORDER BY Items.ItemNumber ASC";
 
            OdbcConnection myConnection = new OdbcConnection(ConnectionString);
            OdbcCommand myCommand = new OdbcCommand(CommandText, myConnection);
 
            myConnection.Open();
 
            DataGrid1.DataSource = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            DataGrid1.DataBind();
 
            // close the connection
            myConnection.Close();
            
        }
    }
 
 
public void chkID_CheckedChanged(object sender, EventArgs e)
   {
       CheckBox chk = sender as CheckBox;
       if (chk != null)
       {
           DataGridItem item = chk.NamingContainer as DataGridItem;
          
           TextBox txt = item.FindControl("price") as TextBox;
           TextBox txt1 = item.FindControl("qty") as TextBox;
           TextBox1.Text=  TextBox1.Text + txt1.Text + " " + "x" + " " + item.Cells[1].Text + " - " + item.Cells[2].Text + "  " + "(" + "$" + txt.Text + ")" + "\n" ;
 
 
           Response.Write("Item List Updated");
           
       }
       
       
   }
 
 
</script>
 
 
 
 
<html>
<head>
</head>
<body style="FONT-FAMILY: arial">
    <form id="Form1" runat="server">
   <asp:HiddenField ID="hiddenField1" runat="server" />  
   <asp:TextBox id="search" runat="server" />
                    
        <asp:datagrid id="DataGrid1" runat="server" CellSpacing="1" GridLines="None" CellPadding="3" BackColor="White" 
ForeColor="Black" EnableViewState="True" Font-Size="8" AutoGenerateColumns="False">
<Columns>
<asp:TemplateColumn HeaderText="Qty">
                <ItemTemplate>
 
         <asp:Textbox columns="1" ID="qty" runat="server" />                       
                                       
                </ItemTemplate>
 
            </asp:TemplateColumn>
                        
 
<asp:BoundColumn HeaderText="Item Number" DataField="ItemNumber" ItemStyle-Font-Size="8" ItemStyle-Font-Name="Arial" />
        <asp:BoundColumn HeaderText="Item Name" DataField="ItemName" ItemStyle-Font-Size="8" ItemStyle-Font-Name="Arial"
                ItemStyle-HorizontalAlign="Left"
                DataFormatString="{0:$#,###.##}" />
<asp:BoundColumn HeaderText="Purchase Price" DataField="TaxInclusiveLastPurchasePrice" ItemStyle-Font-Size="8" ItemStyle-Font-Name="Arial"
                ItemStyle-HorizontalAlign="Left"
                DataFormatString="{0:C}" />  
 
<asp:TemplateColumn HeaderText="Retail Price">
                <ItemTemplate>
 
         <asp:Textbox columns="8" ID="price" runat="server" />                       
                                       
                </ItemTemplate>
 
            </asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Insert">
                <ItemTemplate>
                    <asp:CheckBox ID="chkID" runat="server" 
                        oncheckedchanged="chkID_CheckedChanged" AutoPostBack="True" />
                                       
                </ItemTemplate>
 
            </asp:TemplateColumn>
 </Columns>
            <HeaderStyle font-bold="True" forecolor="white" backcolor="#FF9900" Font-Size="8" Font-Name="Arial" HorizontalAlign="Center"></HeaderStyle>
            <ItemStyle backcolor="#DEDFDE" Font-Name="Arial"></ItemStyle>
 
        </asp:datagrid>
<asp:TextBox ID="TextBox1" TextMode="multiline" columns="74" rows="5" runat="server" />   
    </form>
</body>
</html>

Open in new window

example1.JPG
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Author

Commented:
Just realized that the search box cannot be on the same page as the datarid otherwise I will lose the focus on the search box when it scroll to the row.

Is it possible for me to place the search box outside in a parent I frame that way when I search in the parent iframe it won't lose the textbox but will only automatically scroll to the row in the iframe which contains the datagrid.

Author

Commented:
I take it this can't be done. Is there an easier solution out there someone has already used or is searching a datagrid impossible.

I also found this link whilst searching but it's written in VB.net. I have tried to translate it into C# but have no idea how.

Here is the link: http://www.sitepoint.com/article/datagrid-searching-asp-net/3/

It's basically everything I need but I just don't know how to integrate it with my code.

Any help would be greatly appreciated experts.
Just incase anyone needs a solution to this problem in the future I have found a great solution.

It uses client side javascript.

I use this in Microsoft Dynamics CRM 4.0. I have a text box sitting in a form and an Iframe just below the text box.

Here is complete solution:

Instructions for setting up in Dynamics CRM 4.0

1. Create a new attribute 'nvarchar' and call it anything you like. In the following example I have created a field called 'new_txtsearchbox'.

2. Place the 'new_txtsearchbox' field on the Form containing the iFrame that requires searching. The iFrame you create in Dynamics CRM 4.0 must have the ability to communicate with the parent frame.

3. Change the following lines from the sample below to suit your iFrame

- var frametosearch = 'YOUR_IFRAME_NAME';

If you named your text search box anything other then new_txtsearchbox then please be sure to change anything that says 'new_txtsearchbox' below to suit your text box name.

If your also using this example for anything other than dynamics crm then you must also change the 'crmForm.all' to suit where your form is located. Example 'document.form1'

4. Place the following code in the onload event of the form containing the search box.

You should now have a text box which will search the Iframe contents and hightlight & set focus to the highlighted query.

I like to have the event firing using the 'onchange' method. I still like to place the code in the Onload function of Dynamics CRM and just call the onchange from within the onload.

In the following example I use the search facility for a datagrid which sits inside a frame.

Many Thanks Experts.
// SEARCH ITEMS LIST DATAGRID
 
crmForm.all.new_txtsearchbox.attachEvent ("onchange", dotxtsearchbox);
 
function dotxtsearchbox (){
 
<!-- Hide from old browsers
 
/******************************************
* Find In Page Script -- Submitted/revised by Alan Koontz (alankoontz@REMOVETHISyahoo.com)
* Visit Dynamic Drive (http://www.dynamicdrive.com/) for full source code
* This notice must stay intact for use
******************************************/
 
//  revised by Alan Koontz -- May 2003
 
var TRange = null;
var dupeRange = null;
var TestRange = null;
var win = null;
 
 
//  SELECTED BROWSER SNIFFER COMPONENTS DOCUMENTED AT
//  http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html
 
var nom = navigator.appName.toLowerCase();
var agt = navigator.userAgent.toLowerCase();
var is_major   = parseInt(navigator.appVersion);
var is_minor   = parseFloat(navigator.appVersion);
var is_ie      = (agt.indexOf("msie") != -1);
var is_ie4up   = (is_ie && (is_major >= 4));
var is_not_moz = (agt.indexOf('netscape')!=-1)
var is_nav     = (nom.indexOf('netscape')!=-1);
var is_nav4    = (is_nav && (is_major == 4));
var is_mac     = (agt.indexOf("mac")!=-1);
var is_gecko   = (agt.indexOf('gecko') != -1);
var is_opera   = (agt.indexOf("opera") != -1);
 
 
//  GECKO REVISION
 
var is_rev=0
if (is_gecko) {
temp = agt.split("rv:")
is_rev = parseFloat(temp[1])
}
 
 
//  USE THE FOLLOWING VARIABLE TO CONFIGURE FRAMES TO SEARCH
//  (SELF OR CHILD FRAME)
 
//  If you want to search another frame, change from "self" to
//  the name of the target frame:
//  e.g., var frametosearch = 'main'
 
//var frametosearch = 'main';
var frametosearch = 'YOUR_IFRAME_NAME';
 
 
function search(whichform, whichframe) {
 
//  TEST FOR IE5 FOR MAC (NO DOCUMENTATION)
 
if (is_ie4up && is_mac) return;
 
//  TEST FOR NAV 6 (NO DOCUMENTATION)
 
if (is_gecko && (is_rev <1)) return;
 
//  TEST FOR Opera (NO DOCUMENTATION)
 
if (is_opera) return;
 
//  INITIALIZATIONS FOR FIND-IN-PAGE SEARCHES
 
if(crmForm.all.new_txtsearchbox.value!=null && crmForm.all.new_txtsearchbox.value!='') {
 
       str = crmForm.all.new_txtsearchbox.value;
       win = whichframe;
       var frameval=false;
       if(win!=self)
{
 
       frameval=true;  // this will enable Nav7 to search child frame
       win = parent.frames[whichframe];
 
}
 
    
}
 
else return;  //  i.e., no search string was entered
 
var strFound;
 
//  NAVIGATOR 4 SPECIFIC CODE
 
if(is_nav4 && (is_minor < 5)) {
   
  strFound=win.find(str); // case insensitive, forward search by default
 
//  There are 3 arguments available:
//  searchString: type string and it's the item to be searched
//  caseSensitive: boolean -- is search case sensitive?
//  backwards: boolean --should we also search backwards?
//  strFound=win.find(str, false, false) is the explicit
//  version of the above
//  The Mac version of Nav4 has wrapAround, but
//  cannot be specified in JS
 
 
        }
 
//  NAVIGATOR 7 and Mozilla rev 1+ SPECIFIC CODE (WILL NOT WORK WITH NAVIGATOR 6)
 
if (is_gecko && (is_rev >= 1)) {
   
    if(frameval!=false) win.focus(); // force search in specified child frame
    strFound=win.find(str, false, false, true, false, frameval, false);
 
//  The following statement enables reversion of focus 
//  back to the search box after each search event 
//  allowing the user to press the ENTER key instead
//  of clicking the search button to continue search.
//  Note: tends to be buggy in Mozilla as of 1.3.1
//  (see www.mozilla.org) so is excluded from users 
//  of that browser.
 
    if (is_not_moz)  whichform.findthis.focus();
 
//  There are 7 arguments available:
//  searchString: type string and it's the item to be searched
//  caseSensitive: boolean -- is search case sensitive?
//  backwards: boolean --should we also search backwards?
//  wrapAround: boolean -- should we wrap the search?
//  wholeWord: boolean: should we search only for whole words
//  searchInFrames: boolean -- should we search in frames?
//  showDialog: boolean -- should we show the Find Dialog?
 
 
}
 
 if (is_ie4up) {
 
  // EXPLORER-SPECIFIC CODE revised 5/21/03
 
  if (TRange!=null) {
	  
   TestRange=win.document.body.createTextRange();
 
	  
 
   if (dupeRange.inRange(TestRange)) {
 
   TRange.collapse(false);
   strFound=TRange.findText(str);
    if (strFound) {
        //the following line added by Mike and Susan Keenan, 7 June 2003
        win.document.body.scrollTop = win.document.body.scrollTop + TRange.offsetTop;
        TRange.select();
        }
 
 
   }
   
   else {
 
     TRange=win.document.body.createTextRange();
     TRange.collapse(false);
     strFound=TRange.findText(str);
     if (strFound) {
        //the following line added by Mike and Susan Keenan, 7 June 2003
        win.document.body.scrollTop = TRange.offsetTop;
        TRange.select();
        }
 
 
 
   }
  }
  
   if (TRange==null || strFound==0) {
   TRange=win.document.body.createTextRange();
   dupeRange = TRange.duplicate();
   strFound=TRange.findText(str);
    if (strFound) {
        //the following line added by Mike and Susan Keenan, 7 June 2003
        win.document.body.scrollTop = TRange.offsetTop;
        TRange.select();
        }
 
   
   }
 
 }
 
  if (!strFound) alert ("String '"+str+"' not found!") // string not found
 
        
}
// -->
 
 
{
search(crmForm.all, frametosearch); return false
}
}

Open in new window

search-solution.JPG

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial