Solved

Gridview in TabPanel

Posted on 2007-11-24
3
3,419 Views
Last Modified: 2012-06-27
Hi Experts,

I have a one page(Display.aspx)  ASP.NET project and I am having trouble enabling Paging in a GridView. Can you please take a look?

The projects main objective is to load Car details from a List<Car> into a GridView using an ObjectDataAdapter and display the data in a number of AjaxControl.TabPanel's.

Each Car object in the List<Car> has a public property called  "Type" (string) which servers to identify a Car type e.g. "Nissan", "BMW", "Mazda", etc. Each Type has is loaded into its own Tab(AjaxToolkit.TabPanel). So, for example, we have a Nissan tab which contains a GridView displaying all the Nissan Cars.  

The Gridview(wrapped in a UserControl with a DataObjectAdapter to hook up to a CarAdapter class) loads CarNumber and CarName information in the grid for the CarType(the tab).

My big problem is enabling paging in the GridViews. Firstly, I was getting an Index out of range error so I had to put the code for loading the GridViews into the Page_Init. This fixed the Index out of range issue however it presented me another issue -- namely each time I click on a page number, the page will  refresh and I  the number of pages increases and sometimes the Gridview will be displayed twice. It's as if it is not clearing the old GridView.

Any ideas as to how I may fix this? I am sure it has something to do with moving the code into the Page_Init?

Here are some more details including all the code for the project.
Project Type: C# ASP WebPage
Project Name: TabbedGridView

The full compilable(550kb) project is available for download: http://www.bestsharing.com/f/tuwsV371669
See attached code.

==================================================================================
WebPage Code Behind(Display.aspx) ->Display.cs
==================================================================================
 
protected void Page_Init(object sender, EventArgs e)
{
 for (int n = 0; n < DataObjects.DataCollection.Types.Length; ++n)
 {
  // Load the control that contains the gridview 
  Control ctlGrid = LoadControl("Controls/Grid.ascx");
  // This control contains an ObjectDataSource
  // We need to set the paramater so that we only load particular a
  // subset of the data for in the DataAdapterClass i.e. each tab will   
  // have it's own subset of data
  
  Parameter param = new Parameter("nType");
  param.DefaultValue = n.ToString();
 ((System.Web.UI.WebControls.ObjectDataSource)(ctlGr
  id.Controls[2])).SelectParameters.Add(param);
  TabPanel tpPanel = new TabPanel();
  tpPanel.HeaderText=DataObjects.DataCollection.Types[n];
  tpPanel.Controls.Add(ctlGrid);
  tcTabContainer.Tabs.Add(tpPanel);
 }
}
 
==================================================================================
Display.aspx (Main Page)
==================================================================================
 
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Display.aspx.cs" Inherits="TabbedGridView.Display" %>
 
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ucAjaxTookit" %>
 
<%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI" TagPrefix="asp" %>
 
<!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>Test GridView Display</title>
</head>
<body> 
    <form id="frmDisplay" runat="server">
     <asp:ScriptManager ID="smScriptManager" runat="server"/>
    <div></div>
      <asp:UpdatePanel ID="upDataUpdate"  runat="server">
           <ContentTemplate>                            
                    <ucAjaxTookit:TabContainer ID="tcTabContainer" runat="server" EnableViewState="false" ActiveTabIndex="0" Height="83px" Width="235px" >
                        <ucAjaxTookit:TabPanel ID="tpFirst" Visible="False" runat="server">
                            <ContentTemplate>
                            
                            </ContentTemplate>                                
                        </ucAjaxTookit:TabPanel>                                    
                   </ucAjaxTookit:TabContainer>
                &nbsp;
            </ContentTemplate>
        </asp:UpdatePanel>
    </form>
</body>
</html>
 
======================================================================
Grid.ascx 
======================================================================
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Grid.ascx.cs" Inherits="TabbedGridView.Controls.Grid" %>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" EnableViewState="false" AllowPaging="true" PageSize="3" DataSourceID="odsData">
    <Columns>
        <asp:BoundField DataField="CarNumber" HeaderText="CarNumber" ReadOnly="True" SortExpression="CarNumber" />
        <asp:BoundField DataField="Type" HeaderText="Type" ReadOnly="True" SortExpression="Type" />
        <asp:BoundField DataField="Name" HeaderText="Name" ReadOnly="True" SortExpression="Name" />
    </Columns>
</asp:GridView>
 
<asp:ObjectDataSource ID="odsData" runat="server" SelectMethod="GetAllData" TypeName="TabbedGridView.DataObjects.DataAdapter">
</asp:ObjectDataSource>
 
======================================================================
Car.cs (Business Object)
======================================================================
    public class Car
    {
        private string sName;
        public string Name
        {
            get
            {
                return sName;
            }
        }
 
        private int nCarNumber;
        public int CarNumber
        {
            get
            {
                return nCarNumber;
            }
        }
 
        private string sType;
        public string Type
        {
            get
            {
                return sType;
            }
        }
 
        public Car(string name, int carNumber, string type)
        {
            sName = name;
            nCarNumber = carNumber;
            sType = type;
        }
    }
 
======================================================================
CarAdapter.cs (Business Object)
======================================================================
     public class CarAdapter
    {
        [DataObjectMethod(DataObjectMethodType.Select, true)]
        public List<Car> GetAllData(int nType)
        {
            List<Car> ltTemp = new List<Car>();
            foreach (Car car in CarCollection.DataList)
            {
                if (car.Type == CarCollection.Types[nType])
                {
                    ltTemp.Add(car);
                }
            }
            return ltTemp;
        }
    }
 
 
======================================================================
CarCollection.cs (Business Object) Collection of car objects
======================================================================
  public static class CarCollection
    {
        public static string[] Types = {"Ford", "Nissan", "Mazda", "BMW"};
       
        private static List<Car> ltCars = new List<Car>();
 
        public static List<Car> DataList
        {
            get
            {
                PopulateDataCollection();
                return ltCars;
            }
        }
 
        public static void PopulateDataCollection()
        {            
            int nNumCars = 20;
            for (int nCar = 0; nCar < nNumCars; nCar++)
            {
                string sType = "";
                if (nCar < 5)
                {
                    sType = Types[0];
                }
                else if (nCar < 10)
                {
                    sType = Types[1];
                }
                else if (nCar < 15)
                {
                    sType = Types[2];
                }
                else
                {
                    sType = Types[3];
                }
                Car car = new Car("Car Name " + nCar.ToString(), nCar, sType);
                ltCars.Add(car);
            }
        }
    }

Open in new window

0
Comment
Question by:XPUSR
  • 2
3 Comments
 

Author Comment

by:XPUSR
ID: 20343569
Sorry. I just spotted an error in the code. The list was been appended to on every load however I am still  seeing dublicate gridviews been loaded and displayed on each tab once I click on a page number link.

Here is the update source: http://www.bestsharing.com/files/mJRnR9371692/TabbedGridView.zip.html
0
 
LVL 27

Accepted Solution

by:
Sammy earned 250 total points
ID: 20344948
you were not using the update panel at all
the controls were not added to the update panel
see the code attached and you shouldnt have any problems

C# code
 
        protected void Page_Init(object sender, EventArgs e)
            {
            TabContainer tbContainer = new TabContainer();
                for (int n = 0; n < DataObjects.CarCollection.Types.Length; ++n)
                    {
                    // Load the control that contains the gridview 
                   Control   ctlGrid = LoadControl("Controls/Grid.ascx");
 
                    // This control contains an ObjectDataSource which links to the DataAdapter Class
                    // We need to set the paramater so that we only load a particular subset of the data for in the DataAdapterClass i.e. each tab will have it's own subset of data
                    Parameter param = new Parameter("nType");
                    param.DefaultValue = n.ToString();
                    ((System.Web.UI.WebControls.ObjectDataSource)(ctlGrid.Controls[2])).SelectParameters.Add(param);
                    
            
                    TabPanel tpPanel = new TabPanel();
                    tpPanel.EnableViewState = false;
                    tpPanel.HeaderText = DataObjects.CarCollection.Types[n];
                    tpPanel.Controls.Add(ctlGrid);
                    tbContainer.Controls.Add(tpPanel);
                    holder.Controls.Add(tbContainer);
 
                    }
                }
 
aspx code
 
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Display.aspx.cs" Inherits="TabbedGridView.Display" %>
 
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ucAjaxTookit" %>
 
<%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI" TagPrefix="asp" %>
 
<!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>Test GridView Display</title>
</head>
<body> 
    <form id="frmDisplay" runat="server">
     <asp:ScriptManager ID="smScriptManager" runat="server" EnableViewState="False"/>
    <div></div>
      <asp:UpdatePanel ID="upDataUpdate"  runat="server" EnableViewState="False">
           <ContentTemplate>                            
                   
                            <asp:PlaceHolder id="holder" runat="server"></asp:PlaceHolder>
                   
            
            </ContentTemplate>
        </asp:UpdatePanel>
    </form>
</body>
</html>

Open in new window

0
 
LVL 27

Expert Comment

by:Sammy
ID: 20344969
by the way, the reason why you were seeing duplicates if the fact your update panel was not used
if you look at your code the way it is, when you click on the pager links 1,2,3 the page postsback and there for your loop will run again and creates the same controls all over
0

Featured Post

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

828 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