Solved

Gridview in TabPanel

Posted on 2007-11-24
3
3,394 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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Response.Redirect Open new Form/tab/page? 5 20
Hide Tab Page 3 19
Re-position sub-options beneath the TAB 7 42
Birthdays 3 0
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

758 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

21 Experts available now in Live!

Get 1:1 Help Now