Thursday, February 4, 2010

Show and highlight the searched Record on Top in scrollable DataGrid

This post solve the problem when we search a record from a scrollable gridview or datagrid and the search record will not on the screen till we scroll down. we have a two option either we maintain the scroll position or we put the searched row on top and highlight.
The solution  is....

I just find the row from the datatable which is bind to datagird or gridview....

and create a new row and get the record from searched row ....

and delete the row from that datatable....

and insert the new created row at 0 position of the datatable and highlight it.

here is the source code


for ( int q = 0; q < dsGetDetails.Tables[0].Rows.Count; q++)

{
    //Searh the record
    if (dsGetDetails.Tables[0].Rows[q].ItemArray[0].ToString()== txtEmpId.Text.Trim())

     {
         // Create new row
         DataRow drNew = dsGetDetails.Tables[0].NewRow();
      
       // Loop through current row and copy values to new row
       for (int x = 0; x <= dsGetDetails.Tables[0].Columns.Count - 1; x++)
         {
           drNew[x] = dsGetDetails.Tables[0].Rows[q][x];
         }
     
       // Remove existing row
      dsGetDetails.Tables[0].Rows.RemoveAt(q);

     //Insert new row
    dsGetDetails.Tables[0].Rows.InsertAt(drNew, 0);


    dgDetails.DataSource = dsGetDetails.Tables[0];
    dgDetails.DataBind();


    //Now highlight the row at position 0.
     dgDetails.Items[0].BackColor = System.Drawing.Color.FromName("Red"); 
     break;

   }
}