Expand/Collaspe Gridview > Childview

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dorandoran
    New Member
    • Feb 2007
    • 145

    Expand/Collaspe Gridview > Childview

    I followed Rajib Ahmed's blog and implemented this and it works GREAT. Now that users are happy they want MORE. (They always want more. lol).



    1. I am trying to implement "ShowAll" & "HideAll" button and I tried to follow his suggestion but No success. Can someone please help? I am working on a deadline. I would truly appreciated.

    Code:
    function HideShowAll(divid)
    {
        try
        {
            var j = 0;
            for( j = 0; j < 10; j++)
            {
                var dataid = divid + j;
                HideShowPanel(dataid);
            }
        }
        catch(e)
        {}
    }


    Thanks
    Last edited by Frinavale; Jun 4 '09, 02:50 PM. Reason: Added code tags. Please post code in [code] [/code] tags.
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    Dorandoran could you please post the code that you're using because I don't have want to read that entire article to to guess at what you're doing right or wrong...

    What's the code for the HideShowPanel() method?
    What are you currently doing to call the HideShowAll() method?

    Comment

    • dorandoran
      New Member
      • Feb 2007
      • 145

      #3
      the java file is attached.

      1. I added this to default.aspx page. (and this is outside the gridview ctrl)
      <asp:Hyperlin k id="hlShowAll" runat="server" > Show All</asp:hyperlink>

      2. I added this to default.aspx.cs page (on page)
      this.hlShowAll. Attributes["onclick"]="ShowAll('' " + this.DataGrid1. ClientID + "'');";

      Please let me know. Thanks for the help.


      ====== here is the area on the Rajib's post I was refering to = = = =
      Here is how you can expand all the rows at once:
      1. Drag a hyperlink column to the page, and give it the following id: HLShowALL
      2. Add this code on the Page_Load method, on not postback where the BindData method is:
      Code:
      if ( !Page.IsPostBack )
      {
            //Bind Master Details
            BindData();
            this.HLShowAll.Attributes["onclick"] = "ShowAll(''" + this.DataGrid1.ClientID + "'');";
      }

      3. Add the following function to your javascript file:
      Code:
      function ShowAll(DataGridID)\
      {
      
          var j = 0;
          for( j = 0; j < 10; j++)
          {
              var dataid = "uniquename" + j;
              ShowPanel(dataid);
          }
      }
      
      
      function HideAll(DataGridID)\
      {
      
          var j = 0;
          for( j = 0; j < 10; j++)
          {
              var dataid = "uniquename" + j;
              HidePanel(dataid);
          }
      }
      Attached Files
      Last edited by Frinavale; Jun 4 '09, 05:18 PM. Reason: Added code tags. Please post code in [code] [/code] tags.

      Comment

      • Frinavale
        Recognized Expert Expert
        • Oct 2006
        • 9749

        #4
        Well the following code creates an ID by concatenating the word "uniquename " and the number stored in the variable "j".

        Code:
        function ShowAll(DataGridID)
        {
         
            var j = 0;
            for( j = 0; j < 10; j++)
            {
                var dataid = "uniquename" + j;
                ShowPanel(dataid);
            }
        }
        Do you have any rows or elements in your page (in your GridView) called "uniquename1"," uniquename2",.. .?

        Are you placing the rows into "panels"?

        I'm looking at the ShowPanel() method here:
        Code:
        function ShowPanel(Panel)
        {
        	try
        	{
        		var ChosenPanel = document.all(Panel);
        		if ( ChosenPanel != null )
        		{
        			document.all(Panel).style.display = "block";
        		}
        	}
        	catch(e)
        	{}
        }
        I wouldn't use the document.all() method.
        Instead I would use the document.getEle mentByID() method because you are passing it the ID of the panel/div/row that you want to show ....Same goes for the HideShowPanel() method.


        I have a feeling that this code isn't working because there are probably no elements called "uniquename1"," uniquename2", etc on your page.

        Why don't you post some of the HTML from your GridVIew (when it is rendered in the browser) so that we can take a closer look?

        Comment

        • dorandoran
          New Member
          • Feb 2007
          • 145

          #5
          Actually, this guy wrote the in such a way where he would create div (naming unique1,2,3) etc on run time. hope it's making sense.

          Code:
          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
          <HTML>
          	<HEAD>
          		<title>Datagrid Expand/Collaspe Example</title>
          		<script language="javascript" src="JavaScript/HGridScript.js"></script>
          	</HEAD>
          	<body>
          		<form name="Form1" method="post" action="Default.aspx" id="Form1">
          <input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
          <input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
          <input type="hidden" name="__LASTFOCUS" id="__LASTFOCUS" value="" />
          <input type="hidden" name="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dGlvbjwvdGQ+PHRkPkZsaWdodDwvdGQ+PHRkPlN0YXR1c19OYW1lPC90ZD4NCgk8L3RyPg0KPC90YWJsZT48L0RJVj5kZGSYUBo4hSUdSMjtKOd/hwD3Ec7TVw==" />
          
          <script type="text/javascript">
          <!--
          var theForm = document.forms['Form1'];
          if (!theForm) {
              theForm = document.Form1;
          }
          function __doPostBack(eventTarget, eventArgument) {
              if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
                  theForm.__EVENTTARGET.value = eventTarget;
                  theForm.__EVENTARGUMENT.value = eventArgument;
                  theForm.submit();
              }
          }
          // -->
          </script>
          
          
                      <select name="ddlCategory" onchange="javascript:setTimeout('__doPostBack(\'ddlCategory\',\'\')', 0)" language="javascript" id="ddlCategory" style="font-family:Tahoma;font-size:8pt;width:288px;">
          	<option value="-- Select a Location --">-- Select a Location --</option>
          	<option value="387">ISS Medical Accessory Kit</option>
          	<option selected="selected" value="387">Other</option>
          	<option value="371">PCBA Supplies (IMAK 1030)</option>
          	<option value="101">Respiratory Support Pack </option>
          
          </select>
                      <br />
                      
          			<TABLE id="Table1" height="1" cellSpacing="0" cellPadding="0" width="100%" border="0">
          				<TR>
          					<TD noWrap align="left">
          						<span id="LabelTitle" style="color:Blue;font-family:Tahoma;font-size:14pt;font-weight:bold;height:32px;width:160px;">Sub Locations</span><br />
                                  </TD>
          				</TR>
          				<TR>
          					<TD noWrap align="left">
                                  <a id="hlShowAll">Show All TEST</a>
          						<table cellspacing="0" cellpadding="3" rules="cols" bordercolor="#999999" border="1" id="DataGrid1" style="color:Black;background-color:White;border-color:#999999;border-width:1px;border-style:Solid;width:100%;border-collapse:collapse;">
          	<tr style="color:White;background-color:Black;font-weight:bold;">
          		<td>&nbsp;</td><td>Sub Locations</td>
          	</tr><tr align="left" valign="top" style="font-family:Tahoma;font-size:8pt;">
          		<td id="DataGrid1__ctl3_CellInfo0" onclick="HideShowPanel('uniquename0'); ChangeHLText('DataGrid1__ctl3_CellInfo0'); SetExpanded('DataGrid1__ctl3_CellInfo0','txtExpandedFields');" onmouseover="this.style.cursor='hand'" onmouseout="this.style.cursor='hand'"><a>+</a></td><td>Member Item</td><tr><td bgcolor='f5f5f5'></td><td colspan='1'><DIV id='uniquename0' style='DISPLAY: none; HEIGHT: auto;'><table cellspacing="0" cellpadding="3" rules="all" bordercolor="#CCCCCC" border="1" style="border-color:#CCCCCC;border-width:1px;border-style:solid;font-family:tahoma;font-size:8pt;font-weight:normal;width:100%;border-collapse:collapse;">
          	<tr style="color:White;background-color:SteelBlue;font-family:tahoma;font-size:8pt;font-weight:bold;">
          		<td>Name</td><td>Part</td><td>Serial</td><td>Expiration</td><td>Quantity</td><td>Location</td><td>Flight</td><td>Status_Name</td>
          	</tr>
          </table></DIV></td>
          	</tr><tr align="left" valign="top" style="background-color:#CCCCCC;font-family:Tahoma;font-size:8pt;">
          		<td id="DataGrid1__ctl4_CellInfo1" onclick="HideShowPanel('uniquename1'); ChangeHLText('DataGrid1__ctl4_CellInfo1'); SetExpanded('DataGrid1__ctl4_CellInfo1','txtExpandedFields');" onmouseover="this.style.cursor='hand'" onmouseout="this.style.cursor='hand'"><a>+</a></td><td>Defibrillator</td><tr><td bgcolor='d3d3d3'></td><td colspan='1'><DIV id='uniquename1' style='DISPLAY: none; HEIGHT: auto;'><table cellspacing="0" cellpadding="3" rules="all" bordercolor="#CCCCCC" border="1" style="border-color:#CCCCCC;border-width:1px;border-style:solid;font-family:tahoma;font-size:8pt;font-weight:normal;width:100%;border-collapse:collapse;">
          	<tr style="color:White;background-color:SteelBlue;font-family:tahoma;font-size:8pt;font-weight:bold;">
          		<td>Name</td><td>Part</td><td>Serial</td><td>Expiration</td><td>Quantity</td><td>Location</td><td>Flight</td><td>Status_Name</td>
          	</tr>
          </table></DIV></td>
          	</tr><tr align="center" style="color:Black;background-color:#999999;">
          		<td colspan="2"><span>1</span></td>
          	</tr>
          </table></TD>
          				</TR>
          				<TR>
          					<TD noWrap align="left">
                                  </TD>
          				</TR>
          				<TR>
          					<TD noWrap align="left" style="HEIGHT: 2px">
          						</TD>
          				</TR>
          				<TR>
          					<TD noWrap align="left">
          						</TD>
          				</TR>
          			</TABLE>
          		
          <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWDwLJyP6OAgLh2pKgCgLfw9S7BgKF1NDuCALttcDNBgLvtbjOBgKo/7aZAgL2tZjOBgL2tZTOBgLI9J+aAQKZs5TaAwKuvpAwAoXU7O4IAqPNne8PAqXNue8PKwTqF7qVX7cPwCrU7IoWdLE7F9E=" /></form>
          	</body>
          </HTML>

          Comment

          • Frinavale
            Recognized Expert Expert
            • Oct 2006
            • 9749

            #6
            Something's very wrong here....I'm not sure what you have that's causing your table to rendered as invalid HTML.

            Please post your GridView markup (from your ASP code)

            Comment

            • dorandoran
              New Member
              • Feb 2007
              • 145

              #7
              Please see attached file. Thanks
              Attached Files

              Comment

              • Frinavale
                Recognized Expert Expert
                • Oct 2006
                • 9749

                #8
                I cannot download that due to network settings.
                Please just post the ASP code for your GridView.

                Comment

                • dorandoran
                  New Member
                  • Feb 2007
                  • 145

                  #9
                  Default.aspx

                  Code:
                  <%@ Page language="c#" Inherits="HGrid._Default" CodeFile="Default.aspx.cs" %>
                  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
                  <HTML>
                  	<HEAD>
                  		<title>Datagrid Expand/Collaspe Example</title>
                  		<script language="javascript" src="JavaScript/HGridScript.js"></script>
                  	</HEAD>
                  	<body>
                  		<form id="Form1" method="post" runat="server">
                              <asp:DropDownList ID="ddlCategory" runat="server" Width="288px" Font-Names="Tahoma"  
                              Font-Size="8pt" DataValueField="location_id" DataTextField="location_name"
                               OnSelectedIndexChanged="ddlCategory_SelectedIndexChanged" AutoPostBack="true" >
                              </asp:DropDownList>
                              <br />
                              
                  			<TABLE id="Table1" height="1" cellSpacing="0" cellPadding="0" width="100%" border="0">
                  				<TR>
                  					<TD noWrap align="left">
                  						<asp:Label id="LabelTitle" runat="server" ForeColor="Blue" Font-Bold="True" Font-Names="Tahoma"
                  							Font-Size="14pt" Height="32px" Width="160px">Sub Locations</asp:Label><br />
                                          </TD>
                  				</TR>
                  				<TR>
                  					<TD noWrap align="left">
                                          <asp:HyperLink ID="hlShowAll" runat="server">Show All TEST</asp:HyperLink>
                  						<asp:DataGrid id="DataGrid1" runat="server" AutoGenerateColumns="False" Width="100%" BorderColor="#999999"
                  							BorderStyle="Solid" BorderWidth="1px" BackColor="White" CellPadding="3" GridLines="Vertical"
                  							AllowPaging="True" ForeColor="Black">
                  							<SelectedItemStyle Font-Bold="True" HorizontalAlign="Left" ForeColor="White" VerticalAlign="Top" BackColor="#000099"></SelectedItemStyle>
                  							<EditItemStyle HorizontalAlign="Left" VerticalAlign="Top"></EditItemStyle>
                  							<AlternatingItemStyle HorizontalAlign="Left" BackColor="#CCCCCC"></AlternatingItemStyle>
                  							<ItemStyle Font-Size="8pt" Font-Names="Tahoma" HorizontalAlign="Left" VerticalAlign="Top"></ItemStyle>
                  							<HeaderStyle Font-Bold="True" ForeColor="White" BackColor="Black"></HeaderStyle>
                  							<FooterStyle BackColor="#CCCCCC"></FooterStyle>
                  							
                  							<Columns>
                  								<asp:HyperLinkColumn Text="+"></asp:HyperLinkColumn>
                  								<asp:BoundColumn DataField="subCatID" ReadOnly="True" Visible="False" HeaderText="ID"></asp:BoundColumn>
                  								<asp:BoundColumn DataField="subCatName" HeaderText="Sub Locations"></asp:BoundColumn>
                  							</Columns>
                  							
                  							<PagerStyle HorizontalAlign="Center" ForeColor="Black" BackColor="#999999" Mode="NumericPages"></PagerStyle>
                  						</asp:DataGrid></TD>
                  				</TR>
                  				<TR>
                  					<TD noWrap align="left">
                                          <asp:TextBox id="txtExpandedFields" runat="server" Visible="false"  Width="0px" Font-Names="Tahoma" Font-Size="8pt"></asp:TextBox></TD>
                  				</TR>
                  				<TR>
                  					<TD noWrap align="left" style="HEIGHT: 2px">
                  						</TD>
                  				</TR>
                  				<TR>
                  					<TD noWrap align="left">
                  						</TD>
                  				</TR>
                  			</TABLE>
                  		</form>
                  	</body>
                  </HTML>













                  =========== default.aspx.cs =============== ===

                  Code:
                  using System;
                  using System.Collections;
                  using System.ComponentModel;
                  using System.Data;
                  using System.Drawing;
                  using System.Web;
                  using System.Web.SessionState;
                  using System.Web.UI;
                  using System.Web.UI.WebControls;
                  using System.Web.UI.HtmlControls;
                  
                  namespace HGrid
                  {
                  	public partial class _Default : System.Web.UI.Page
                  	{
                  		protected void Page_Load(object sender, System.EventArgs e)
                  		{
                  			if ( !Page.IsPostBack )
                  			{
                                  //Bind Location
                                  FillCategeries();
                  				//Bind Master Details
                  				BindData();
                                  
                                  //this.hlShowAll.Attributes["onClick"] = "ShowAll(''" + this.DataGrid1.ClientID + "'');";
                  			}
                  			else
                  			{
                  				//If it is a postback that is not from the grid, we have to expand the rows
                  				//the user had expanded before.  We have to check first who called this postback
                  				//by checking the Event Target
                  				if ( Request["__EVENTTARGET"] != null)
                  				{
                  					string strEventTarget = Request["__EVENTTARGET"].ToString().ToLower();
                  					if ( strEventTarget.IndexOf("datagrid1") == -1)
                  					{
                  						//Expanded what ever the user had expanded by Setting Mode
                  						//which will be used in ItemDataBound method.
                  						ViewState["Mode"] = "ShowDetails";
                  						//Not caused by datagrid
                  						//We need to rebind data and generate scripts.
                  						BindData();
                  					}
                  					else
                  					{
                  						ViewState["Mode"] = null;
                  					}
                  				}
                  
                  			}
                  		}
                  
                  		private void BindData()
                  		{
                              if ((ddlCategory.SelectedValue == "-- Select a Location --") | (ddlCategory.SelectedValue == "0"))
                              { }
                              else
                              {
                                  int scID = Convert.ToInt32(ddlCategory.SelectedValue);
                                  if (scID != null)
                                  {
                                      clsDataBindGrid fsc = new clsDataBindGrid();
                                      DataGrid1.DataSource = fsc.FillSubCategories(scID);
                                      DataGrid1.DataBind();
                                  }
                              }
                  		}
                  
                          void FillCategeries()
                          {
                              ddlCategory.SelectedIndex=0;
                              clsDataBindGrid fc = new clsDataBindGrid();
                              ddlCategory.DataSource = fc.FillCategories();
                              ddlCategory.DataBind();
                              ddlCategory.Items.Insert(0, new ListItem("-- Select a Location --"));
                              ddlCategory.SelectedIndex = 0;
                  
                          }
                  
                  		#region Web Form Designer generated code
                  		override protected void OnInit(EventArgs e)
                  		{
                  			//
                  			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
                  			//
                  			InitializeComponent();
                  			base.OnInit(e);
                  		}
                  		
                  		/// <summary>
                  		/// Required method for Designer support - do not modify
                  		/// the contents of this method with the code editor.
                  		/// </summary>
                  		private void InitializeComponent()
                  		{    
                  			this.DataGrid1.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.DataGrid1_PageIndexChanged);
                  			this.DataGrid1.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemDataBound);
                  
                  		}
                  		#endregion
                  
                  		#region Datagrid Methods
                  		private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
                  		{
                  			if ( e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem )
                  			{
                                  clsDataBindGrid dsProducts = new clsDataBindGrid();
                  
                  				//For better performance, do not use a grid and bind labels, textbox's, etc...
                  				DataGrid NewDg = new DataGrid();
                  				NewDg.AutoGenerateColumns = true;
                  				NewDg.Width = Unit.Percentage(100.00);                
                                  NewDg.DataSource = dsProducts.FillProducts(Convert.ToInt32(e.Item.Cells[1].Text)); 
                  				NewDg.DataBind();
                  				
                  				SetProps(NewDg);
                  
                  				System.IO.StringWriter sw = new System.IO.StringWriter();
                  				System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
                  				NewDg.RenderControl( htw );
                  
                  				string DivStart = "<DIV id='uniquename" + e.Item.ItemIndex.ToString() +"' style='DISPLAY: none; HEIGHT: auto;'>";
                  				string DivBody = sw.ToString();
                  				string DivEnd = "</DIV>";
                  				string FullDIV = DivStart + DivBody + DivEnd;
                  					
                  				int LastCellPosition = e.Item.Cells.Count - 1;
                  				int NewCellPosition = e.Item.Cells.Count - 2;
                  				
                  				e.Item.Cells[0].ID = "CellInfo" + e.Item.ItemIndex.ToString();
                  
                  				if ( ViewState["Mode"] != null && ViewState["Mode"].ToString() == "ShowDetails")
                  				{
                  					if ( this.txtExpandedFields.Text.IndexOf(e.Item.Cells[0].ClientID) != -1 )
                  					{
                  						//make it expand.
                  						FullDIV = FullDIV.Replace("DISPLAY: none","DISPLAY: block");
                  						e.Item.Cells[0].Text = "<A>-</A>";
                  					}
                  				}
                  
                  				//match color
                  				if (e.Item.ItemType == ListItemType.Item)
                  				{
                  					e.Item.Cells[LastCellPosition].Text = e.Item.Cells[LastCellPosition].Text + "</td><tr><td bgcolor='f5f5f5'></td><td colspan='" + NewCellPosition +"'>" + FullDIV;
                  				}
                  				else
                  				{
                  					e.Item.Cells[LastCellPosition].Text = e.Item.Cells[LastCellPosition].Text + "</td><tr><td bgcolor='d3d3d3'></td><td colspan='" + NewCellPosition +"'>" + FullDIV;
                  				}
                  				e.Item.Cells[0].Attributes["onclick"] = "HideShowPanel('uniquename" + e.Item.ItemIndex.ToString() + "'); ChangeHLText('" + e.Item.Cells[0].ClientID + "'); SetExpanded('" + e.Item.Cells[0].ClientID + "','" + txtExpandedFields.ClientID + "');";
                  				e.Item.Cells[0].Attributes["onmouseover"] = "this.style.cursor='hand'";
                  				e.Item.Cells[0].Attributes["onmouseout"] = "this.style.cursor='hand'";
                  				
                  			}
                  		}
                  
                  		private void DataGrid1_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
                  		{
                  			//clean up expanded records.
                  			txtExpandedFields.Text = "";
                  			DataGrid1.CurrentPageIndex = e.NewPageIndex;
                  			BindData();
                  		}
                  
                  		public void SetProps(System.Web.UI.WebControls.DataGrid DG)
                  		{
                  			/****************************************************************************/
                  			DG.Font.Size = 8;
                  			DG.Font.Bold = false;
                  			DG.Font.Name = "tahoma";
                  
                  			/*******************************Professional 2**********************************/
                  			//Border Props 
                  			DG.GridLines = GridLines.Both;
                  			DG.CellPadding = 3;
                  			DG.CellSpacing = 0;
                              
                  			DG.BorderColor = System.Drawing.Color.FromName("#CCCCCC");
                  			DG.BorderWidth = System.Web.UI.WebControls.Unit.Pixel(1);
                  
                  			
                  			//Header Props
                  			DG.HeaderStyle.BackColor = System.Drawing.Color.SteelBlue;
                  			DG.HeaderStyle.ForeColor = System.Drawing.Color.White;
                  			DG.HeaderStyle.Font.Bold = true;
                  			DG.HeaderStyle.Font.Size = 8;
                  			DG.HeaderStyle.Font.Name = "tahoma";
                  
                  			DG.ItemStyle.BackColor = System.Drawing.Color.LightSteelBlue;
                  
                  		}
                  
                  		#endregion
                  
                          protected void ddlCategory_SelectedIndexChanged(object sender, EventArgs e)
                          {
                              if ((ddlCategory.SelectedValue == "-- Select a Location --") | (ddlCategory.SelectedValue == "0"))
                              {
                                  Response.Redirect("default.aspx");
                              }
                              else
                              {
                                  int scID = Convert.ToInt32(ddlCategory.SelectedValue);
                                  clsDataBindGrid fsc = new clsDataBindGrid();
                                  DataGrid1.DataSource = fsc.FillSubCategories(scID);
                                  DataGrid1.DataBind();
                              }
                          }
                         
                  	}
                  }

                  Comment

                  • Frinavale
                    Recognized Expert Expert
                    • Oct 2006
                    • 9749

                    #10
                    I ran into a few problems with FireFox/Visual Studio.
                    What you have here is hard for me to read.

                    No wonder your HTML is invalid.
                    You have a Table, and within the Table you have a GridView (another table) and within the GridView you have more GridViews (more tables).....

                    It's going to be very hard to track down the missing tags and other invalid HTML.

                    I would strongly recommend you upgrade to using a GridView, and use a TemplateField to accomplish what you want. (And stay away from using tables to lay out your page)

                    Comment

                    • dorandoran
                      New Member
                      • Feb 2007
                      • 145

                      #11
                      I basically took this guys code and change few things here and there insead of re-inventing the wheel.

                      Comment

                      • Frinavale
                        Recognized Expert Expert
                        • Oct 2006
                        • 9749

                        #12
                        Honestly I think that re-inventing the wheel is much easier than trying to look at that article. The article is using too many controls and is bloating your page.

                        Since it's easy for me to "re-invent the wheel", here's a Very simple example of expanding and collapsing details. (Note how little clutter there is in the ASP, HTML and Server code compared to the article you were following)

                        I'm using a GridView (not a DataGrid) along with TemplateFields

                        Code:
                        <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="WebForm3.aspx.vb" Inherits="ScratchPad.WebForm3" %>
                        
                        <!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></title>
                        
                            <script type="text/javascript">
                                function ExpandCollapse(detailsSectionID) {
                                    var detailsSection = document.getElementById(detailsSectionID);
                                    if (detailsSection) {
                                        if (detailsSection.style.display == "none") {
                                            detailsSection.style.display = "block";
                                        } else {
                                            detailsSection.style.display = "none";
                                        }
                                    }
                                }
                            </script>
                        
                        </head>
                        <body>
                            <form id="form1" runat="server">
                            <div>
                                <asp:GridView ID="ItemsGrid" runat="server" AutoGenerateColumns="false">
                                    <Columns>
                                        <asp:TemplateField HeaderText="Expand Details">
                                            <ItemTemplate>
                                                <asp:HyperLink ID="ExpandCollapse" runat="server" Text="+/-"></asp:HyperLink>
                                            </ItemTemplate>
                                        </asp:TemplateField>
                                        <asp:TemplateField HeaderText="Items">
                                            <ItemTemplate>
                                                <div style="width: 100%; text-align: center">
                                                    <%#Eval("subCatName") %></div>
                                                <asp:Panel ID="ItemDetails" runat="server" Style="display: none">
                                                    <table border="1px">
                                                        <thead>
                                                            <tr>
                                                                <th>
                                                                    ID
                                                                </th>
                                                                <th>
                                                                    Name
                                                                </th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <tr>
                                                                <td>
                                                                    <%#Eval("subCatID")%>
                                                                </td>
                                                                <td>
                                                                    <%#Eval("subCatName") %>
                                                                </td>
                                                            </tr>
                                                        </tbody>
                                                    </table>
                                                </asp:Panel>
                                            </ItemTemplate>
                                        </asp:TemplateField>
                                    </Columns>
                                </asp:GridView>
                            </div>
                            </form>
                        </body>
                        </html>
                        Sorry but I work in VB:
                        Code:
                        Partial Public Class WebForm3
                            Inherits System.Web.UI.Page
                            Private _gridViewDataSource As DataView
                        
                            Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
                                Dim someTable As New DataTable
                                someTable.Columns.Add("subCatID")
                                someTable.Columns.Add("subCatName")
                        
                                For i As Integer = 0 To 5
                                    Dim dr As DataRow
                                    dr = someTable.NewRow
                                    dr("subCatID") = "subCatID" + i.ToString
                                    dr("subCatName") = "subCatName" + i.ToString
                                    someTable.Rows.Add(dr)
                                Next
                                _gridViewDataSource = New DataView(someTable)
                                ItemsGrid.DataSource = _gridViewDataSource
                                ItemsGrid.DataBind()
                            End Sub
                        
                            Private Sub ItemsGrid_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles ItemsGrid.RowDataBound
                                Dim expandCollapseLink As HyperLink = CType(e.Row.FindControl("ExpandCollapse"), HyperLink)
                                Dim detailsSection As Panel = CType(e.Row.FindControl("ItemDetails"), Panel)
                                If expandCollapseLink IsNot Nothing AndAlso detailsSection IsNot Nothing Then
                                    expandCollapseLink.Attributes.Add("onclick", "ExpandCollapse('" + detailsSection.ClientID + "');")
                                End If
                        
                            End Sub
                        End Class


                        Basically what I did was use TemplateFields to configure the data into elements that I could actually use with JavaScript.....

                        I added JavaScript to the page that expands and collapses the data that I want to expand and collapse.

                        In my VB Code I implement a method that handles the GridView's RowDataBound event...at which time I grab the hyperlink that controls the expand/collapse feature and add the JavaScript that should be called when the link is clicked.


                        Take a look at my code and feel free to ask me any questions you want to about what I'm doing.

                        Comment

                        • Frinavale
                          Recognized Expert Expert
                          • Oct 2006
                          • 9749

                          #13
                          Here's the C# Translation:
                          (
                          can't test it here so it may be a little invalid.
                          oh yeah, the ASP stuff stays the same
                          )

                          Code:
                             private DataView _gridViewDataSource;
                          
                              protected void Page_Load(Object sender,  System.EventArgs e) 
                             {
                                  DataTable someTable = New DataTable();
                                  someTable.Columns.Add("subCatID");
                                  someTable.Columns.Add("subCatName");
                                  Integer i;
                                   for(i= 0; i<= 5;i++)
                                  {
                                      DataRow dr;
                                      dr = someTable.NewRow();
                                      dr["subCatID"] = "subCatID" + i.ToString();
                                      dr["subCatName"] = "subCatName" + i.ToString();
                                      someTable.Rows.Add(dr);
                                  }
                                  _gridViewDataSource = new DataView(someTable);
                                  ItemsGrid.DataSource = _gridViewDataSource;
                                  ItemsGrid.DataBind();
                              }
                          
                              Private void ItemsGrid_RowDataBound(Objectsender, System.Web.UI.WebControls.GridViewRowEventArgs e )
                              {
                                  HyperLink expandCollapseLink = (HyperLink)e.Row.FindControl("ExpandCollapse");
                                  Panel  detailsSection = (Panel)e.Row.FindControl("ItemDetails");
                                  If(expandCollapseLink != null && detailsSection != null)
                                  {
                                      expandCollapseLink.Attributes.Add("onclick", "ExpandCollapse('" + detailsSection.ClientID + "');");
                                  }
                          
                              }

                          Comment

                          • Frinavale
                            Recognized Expert Expert
                            • Oct 2006
                            • 9749

                            #14
                            Now that I have a working simple solution I've added the JavaScript required to expand and collapse all of the detail sections on the page.

                            The back end server code doesn't have to change for this to work....you just need to change the JavaScript to this:

                            Code:
                                <script type="text/javascript">
                                    function ExpandCollapse(detailsSectionID) {
                                        var detailsSection = document.getElementById(detailsSectionID);
                                        if (detailsSection) {
                                            if (detailsSection.style.display == "none") {
                                                detailsSection.style.display = "block";
                                            } else {
                                                detailsSection.style.display = "none";
                                            }
                                        }
                                    }
                                    function ExpandAll() {
                                        var allDivElements = document.getElementsByTagName("div");
                                        var numElements = allDivElements.length;
                                        
                                        var pattern=new RegExp("ItemDetails")
                                        for (var i = 0; i < numElements; i++) {
                                            if (pattern.test(allDivElements[i].id)) {
                                                allDivElements[i].style.display = "block";
                                            }
                                        }
                            
                                    }
                                    function CollapseAll() {
                                        var allDivElements = document.getElementsByTagName("div");
                                        var numElements = allDivElements.length;
                            
                                        var pattern = new RegExp("ItemDetails")
                                        for (var i = 0; i < numElements; i++) {
                                            if (pattern.test(allDivElements[i].id)) {
                                                allDivElements[i].style.display = "none";
                                            }
                                        }
                                    }    
                                </script>

                            Comment

                            • dorandoran
                              New Member
                              • Feb 2007
                              • 145

                              #15
                              Sorry for being late. I left work early, went to Gym, now home. Long day. Thanks for all the code. I am about to try and will post a feedback.

                              AGAIN, THANKS A LOOOTTTTT FOR YOUR HELP, TIME AND BEING GENEROUS.

                              Comment

                              Working...