Question

How to I hide and show GridView rows in Javascript

Asked by: karakav

I am developing a web application in ASP.NET 2.0 with C# code behind and data stored in SQL Server 2005. I have a GridView that gets the data from a SQL Server and whose purpose is to allow the user to select a row from the GridView and have the column ID value (Primary key) of the selected row being populated in a list box and disappear in the GridView. When the user later remove the value from the listbox, the corresponding row has to appear again on the gridview. I tried to use "row.parentElement.parentElement.style.visibility="hidden" this only hide the data but not the actual row.
Another difficulty is that the gridview allows paging, which refreshes the page upon pagination. Can anyone help me solve this?

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2008-07-25 at 00:33:01ID23594780
Tags

Visual Studio (Visual Web Developer)

,

2005

,

C#

,

Internet Explorer 7

Topics

Programming for ASP.NET

,

Asynchronous Javascript and XML (AJAX)

,

JavaScript

Participating Experts
1
Points
500
Comments
9

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. asp.net gridview
    I am currently using javascript, asp.net and c# in my application. Originally i created a table and got values from that table in javascript and c#. My problem is that instead of using a table i will need to use a gridview with paging (to minimize the height of the data view...
  2. selecting checkboxes from multiple pages(means from pag…
    Hi, I am workin on C# using ASP.net 2.0 I am showing my records in Gridview My gridview has the checkboxes with each row User should be able to check the checkboxes from multiple pages using the pagination. Here I mean if user selects some values from page 1 and then go ...
  3. gridview in asp.net
    i have to display data in gridview asp.net 2.0.problem is that one of my column contains text box in gird view?i have to update another column's value of gird view based on text box 's value of gird column, without sending it to server?lest we have three columns in grid view ...
  4. Pagination
    Currently i m working in asp.net as front end and sqlserver as back end My question is: As we do pagination in Gridview view control, i need to know can we do pagination on a page itself or in panel control. On a page, i m retrieving 5 records which includes images and its ...
  5. How can I speed up the rendering of a gridview with no pa…
    I have a gridview on a page (5 columns returned from a SQL Server 2005 database & 1 checkbox column) I don't have pagination specified on the page because the user needs the ability to select 0 to many rows. I also have a textbox with a button with javascript behind the...
  6. GridView - Pagination - Total Record Count
    I am databinding a GridView to a DataTable, via an ObjectDataSource. I have enabled pagination and would like to display pagination data on the GUI as follows: Displaying [Index of 1st Record on GridView.Page] - [Index of last Record on GridView.Page] of [GridView's total r...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: b1xml2Posted on 2008-07-30 at 07:53:13ID: 22121006

The answer lies in the following:

  1. Keep the list of IDs 
  2. Pass the list of IDs into the method/controller/factory that makes the call to SQL Server. By passing the list of IDs to the data tier, you allow paging to occur without including the list of ids.
     
You can pass say a pipe delimited string containing the ids into a stored proc which converts the ids into a table via a function and thus filters out the data in the resultset SQL-side.

This will handle the paging issue.

What is needed is to remove the row without actually removing the underlying data. I suppose when a row is removed, a rebinding occurs because of pagination. If this is the case, then the solution to the paging issue also solves how rows are removed or added back to the GridView.

Below is a working example against the AdventureWorks database which comes as a sample with SQL Server 2005.

  1. The function ufnGetTableFromIDList created inside the Adventure Works provides the filtering. 
  2. The entity class provides a business-object centric approach 
  3. The factory class allows for consumption by the ObjectDataSource control. If you use LINQ-to-SQL classes in .NET 3.5, your code becomes considerably less and easier to maintain. I have elected to use .NET 2.0-esque  code without resorting to any ORM Framework that might muddy the example. The SQL statement uses server-side paging, a fact that will not go unnoticed when your records number in the thousands or hundreds of thousands.
     
  4. Notice the ContactObjectDataSource_Selecting  method which is where the filters are injected and bubbled all the way up to SQL Server. 


SQL Function To Handle Filters:

create function ufnGetTableFromIDList(@list varchar(max))
returns @table table
(
   Id int primary key not null
)
as
begin
   declare @data varchar(max), @index int;
   set @data = @list;
   while len(@data) > 0
   begin
       set @index = charindex('|',@data);
       if @index = 0
       begin
           insert @table
           select convert(int,@data)

           set @data = '';
       end
       else
       begin
           insert @table
           select convert(int,left(@data,@index - 1))

           set @data = substring(@data, @index + 1, len(@data) - @index)
       end


       

   end
   return;
end

Entity Class

using System;

namespace ExpertsExchange.Q23594780
{
   [Serializable]
   public class Contact
   {
       private int _id;

       public int Id
       {
           get { return _id; }
           set { _id = value; }
       }

       private string _firstName;

       public string FirstName
       {
           get { return _firstName; }
           set { _firstName = value; }
       }


       private string _lastName;

       public string LastName
       {
           get { return _lastName; }
           set { _lastName = value; }
       }

       private string _email;

       public string Email
       {
           get { return _email; }
           set { _email = value; }
       }
   }
}

Factory Class

using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics;

namespace ExpertsExchange.Q23594780
{
   [DataObject]
   public class ContactFactory
   {
       private const string SELECT_COMMAND = @"select * from
       (
           select
           row_number() over(order by a.LastName, a.FirstName) as RowNumber,
           a.ContactID,
           a.FirstName,
           a.LastName,
           a.EmailAddress
       from
           (
               select
                    *
                from
                    Person.Contact
                where
                    ContactID not in (select Id from dbo.ufnGetTableFromIDList(@filters))
           ) a
       ) b
       where
           b.RowNumber between @startRowIndex + 1 and (@startRowIndex + @maximumRows)";

       private const string COUNT_COMMAND = @"select count(*) from Person.Contact where ContactID not in (select Id from dbo.ufnGetTableFromIDList(@filters))";


       private SqlConnection GetConnection()
       {
           return new SqlConnection("Data Source=.;Initial Catalog=AdventureWorks;Trusted_Connection=Yes;");
       }

       public int GetContactsCount(string filters)
       {
           try
           {
               using (SqlConnection connection = GetConnection())
               {
                   try
                   {
                       connection.Open();
                       using (SqlCommand command = new SqlCommand(COUNT_COMMAND, connection))
                       {
                           command.Parameters.AddWithValue("@filters", filters);
                           int count = (int)command.ExecuteScalar();
                           return count;
                       }
                   }
                   catch
                   {
                       throw;
                   }
                   finally
                   {
                       connection.Close();
                   }


               }
           }
           catch (Exception ex)
           {
               Trace.WriteLine(ex.Message);
               return 0;
           }

       }

       [DataObjectMethod(DataObjectMethodType.Select,true)]
       public List<Contact> GetContacts(string filters, int startRowIndex, int maximumRows)
       {  
            try
           {
               using (SqlConnection connection = GetConnection())
               {
                   try
                   {
                       connection.Open();
                       using (SqlCommand command = new SqlCommand(SELECT_COMMAND,connection))
                       {
                           List<Contact> list = new List<Contact>();

                           command.Parameters.AddWithValue("@startRowIndex", startRowIndex);
                           command.Parameters.AddWithValue("@maximumRows", maximumRows);
                           command.Parameters.AddWithValue("@filters", filters);
                           using (SqlDataReader reader = command.ExecuteReader())
                           {
                               while (reader.Read())
                               {
                                   Contact item = new Contact();
                                   item.Id = (int)reader["ContactID"];
                                   item.FirstName = (string)reader["FirstName"];
                                   item.LastName = (string)reader["LastName"];
                                   item.Email = (string)reader["EmailAddress"];
                                   list.Add(item);

                               }
                               reader.Close();
                           }
                           return list;

                       }
                   }
                   catch
                   {
                       throw;
                   }
                   finally
                   {
                       connection.Close();
                   }

               }

           }
           catch (Exception ex)
           {
               Trace.WriteLine(ex.Message);
               return new List<Contact>();
           }
       }
       
   }
}

ASPX File

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ExpertsExchange.Q23594780.Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
   <title>Q23594780</title>
</head>
<body>
   <form id="form1" runat="server">
   <div>
       <asp:GridView ID="ContactGridView" runat="server"
            DataSourceID="ContactObjectDataSource" AllowPaging="True" DataKeyNames="Id,FirstName,LastName,Email"
           AutoGenerateColumns="False">
           <Columns>
               <asp:TemplateField>
               <ItemTemplate>
               <asp:Button ID="RemoveButton" runat="server" OnClick="RemoveButton_Click" Text="Remove"/>
               </ItemTemplate>
               </asp:TemplateField>
               <asp:BoundField DataField="FirstName" HeaderText="First Name" />
               <asp:BoundField DataField="LastName" HeaderText="Last Name" />
               <asp:TemplateField HeaderText="Email">
               <ItemTemplate>
               <a href='<%# Eval("Email","mailto:{0}") %>'><%# Eval("Email") %></a>
               </ItemTemplate>
               </asp:TemplateField>
           </Columns>
       </asp:GridView>
   </div>
   <div>
   <asp:ListBox ID="SelectedFiltersListBox" runat="server" Width="500px">
   
   </asp:ListBox>
   <asp:Button ID="RemoveFilterItemButton" runat="server" Text="Remove Filter" OnClick="RemoveFilterItemButton_Click" />
   </div>
   <asp:ObjectDataSource ID="ContactObjectDataSource" runat="server"
        TypeName="ExpertsExchange.Q23594780.ContactFactory"
        OldValuesParameterFormatString="{0}" SelectMethod="GetContacts"
        EnablePaging="True" SelectCountMethod="GetContactsCount"
        onselecting="ContactObjectDataSource_Selecting">
       <SelectParameters>
           <asp:Parameter Name="filters" Type="String" />
       </SelectParameters>
   </asp:ObjectDataSource>
   </form>
</body>
</html>

Code-Behind

using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI.WebControls;

namespace ExpertsExchange.Q23594780
{
   public partial class Default : System.Web.UI.Page
   {
       protected void Page_Load(object sender, EventArgs e)
       {

       }

       protected void RemoveButton_Click(object sender, EventArgs e)
       {
           GridViewRow row = (GridViewRow)((Button)sender).NamingContainer;
           DataKey key = ContactGridView.DataKeys[row.RowIndex];
           string text = string.Format("{0}, {1} ({2})", key["LastName"], key["FirstName"], key["Email"]);
           string value = key["Id"].ToString();
           this.SelectedFiltersListBox.Items.Add(new ListItem(text,value));
           this.ContactGridView.DataBind();
       }

       protected void ContactObjectDataSource_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
       {
           List<string> list = new List<string>();
           foreach (ListItem item in this.SelectedFiltersListBox.Items)
           {
               list.Add(item.Value);
           }
           string filters = string.Join("|", list.ToArray());
           e.InputParameters[0] = filters;

       }

       protected void RemoveFilterItemButton_Click(object sender, EventArgs e)
       {
           if (this.SelectedFiltersListBox.SelectedIndex != -1)
           {
               this.SelectedFiltersListBox.Items.RemoveAt(this.SelectedFiltersListBox.SelectedIndex);
               this.ContactGridView.DataBind();
           }
       }
   }
}

 

by: b1xml2Posted on 2008-07-30 at 08:06:53ID: 22121170

Hiding or unhiding grid rows in Javascript is not a solution because of the fact that pagination causes any javascript solution to go wonky, unless you can pass up the filters all the way to the factory as shown with this server-side example.

The example I show you was handwritten under 30 minutes.

By wrapping up the controls (except the Object Data Source) inside an Update Panel, you have the best of both worlds. I leave that extra bit for your exercise.


 

by: b1xml2Posted on 2008-07-30 at 08:18:12ID: 22121301

To recap,

  1. The filters determine what rows are not to be considered SQL-side when returning  paged set. 
  2. This filters are provided whenever the GridView is bound via the Selecting method on the Object Data Source which gets called. 
  3. When the filters are removed from the ListBox a rebind occurs placing back the item onto the GridView. 
  4. Javascript alone cannot do what you want since we are dealing with both data and server-controls along with the much vaunted ViewState as well 
  5. The example provided allows for a robust solution without any recourse to Javascript. 
Happy coding and hope this helps!

 

by: karakavPosted on 2008-07-30 at 16:52:57ID: 22125898

Thank you very much for you elaborated response. However, I was not able to run the application as I got the following error: The type specified in the TypeName property of ObjectDataSource 'ContactObjectDataSource' could not be found.
The application compiles fine and I don't know what is wrong here. Do you mind have another look again. I have VS 2005 Professional and .NET 2.0 installed. I used VS internal server. My machine has Vista Ultimate installed.

Thanks. Here  is all the projects attached.

 

by: b1xml2Posted on 2008-07-30 at 19:43:44ID: 22126570

  1. Convert the web site to a web application project if necessary. 
  2. What you face is a namespace problem, look at your class view or reflector and get the correct namespace of the factory class.
     
  3. My project is a web application named as ExpertsExchange with a folder Q23594780 created and holding the items that you see. 

 

by: b1xml2Posted on 2008-07-30 at 21:49:19ID: 22126965

Attached herewith is the project files that you add to your web application. It should work as is. Please remove the .txt extension as the *.cs extension is not allowed in zipped files on EE.

  • Q23594780.zip
    • 3 KB

    Project Items (please remove *.txt extension)

 

by: karakavPosted on 2008-08-01 at 07:41:39ID: 22138708

Thank you very much b1xm2. I have to apologize as I didn't react on time about you interesting update I must say again. I was actually trying to make the solution work on normal as asp.net website with no success. But I finally managed to make it with web application project. Thanks you very much for you support. As a final request, would do you mind to give me information where I can read more about SQL server functions?

 

by: b1xml2Posted on 2008-08-02 at 00:26:41ID: 22143387

i tend to google what i need from sql functions but by and large, they are quite simple to create. Reading up the SQL Server (within the SQL Trans-act section) Help Documentation will give you gems of coding possibilities.

 

by: karakavPosted on 2008-08-03 at 09:55:02ID: 22148094

Thanks again for your help. I will google for more information.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...