ProgTalk - Your archive for all source code

How to collapse and expand rows of a datagrid using C#, ASP.NET, and Javascript. (Version 2)

ProgTalk » Articles » .NET, C#, ASP.NET, Javascript » How to collapse and expand rows of a datagrid using C#, ASP.NET, and Javascript. (Version 2)
 
Author: Rajib A.
Page Views: 35608
Average Article Rating: rating starrating starrating starquarter star
 

What is HGrid?

HGrid stands for Hierarchy Grid.  This grid is meant to hold data using a datagrid/table, and present it to users in a fashionable manner. 

 Looking for this code in VB.NET?

VB.NET Version

What is this article about?

The following article will describe the source code, which will allow programmers to create a HGrid.  It will allow master/slave or master/child data to be shown.  It also includes the features to collapse and expand data on the client side using JavaScript.  The original code was done in Visual Studio 2003 using framework 1.1.  This is the second version of this grid. 

 

Why the second version?

The original had a flaw where I had to bind the data both on the “!Page.IsPostBack”, and “Page.IsPostBack” of the page load to ensure that the state of expansion of the rows of the grid were maintained.  I did not like the fact that I had to connect to the database again for a query.  It did not seem efficient.  I also wanted to add basic sorting features, and give more detail to beginner programmers on using the code.  I also had to modify the JavaScript methods to handle a few bugs I had missed out on.

 

What are the controls needed?

In order to create a HGrid on your own, only a datagrid, and a hidden textbox are needed.  In the example I have included the following are the components:

1.     DataGrid          (ID: DataGrid1)

The datagrid will hold the data for the master/slave or master/child data.  We will also include the feature to expand/collapse (show/hide) on the grid itself.  In the example I use, I will be connecting to the NorthWind database of a SQL Database.

2.      TextBox           (ID: txtExpandedDivs, Width = “0px” or in a div which has style.display: 'none') 

The width is set to 0px so that the users cannot see it, but it exists on the page as a hidden text field.  I chose to do it this way, so users can change the width and view the contents of the textbox

3.   Button              (ID: ButtonSample)

This button is outside of the grid.  I created this button, but most likely when users create a page, the page will consist of many controls which will call the page to reload.  We have to make sure the contents of the grid are the same, once the page is refreshed.

4.   Labels              (ID: LabelPostBack)

This label will show the contents of the hidden textbox (txtExpandedDivs) once the (ButtonSample) is clicked.

5.   Labels              (ID: LabelTitle)

This label is just show the database we are connecting to.  e.g.. NorthWind

6.   Labels              (ID: LabelWhatHappens)

This label is a static label which always shows the message:  “What are we storing in the hidden textbox field (txtExpandedDivs Textbox Control)?”

7.   Table                (ID: Table1)

This table has all the above controls in it.

Details of the DataGrid

Here is the html of the datagrid below.  It has paging (10 per page), sorting, and autogeneratedcolumns = false.  The columns we have are:

  1. HyperLinkColumn: “+”
  2. BoundColumn: “OrderID”, “CustomerID”, “EmployeeID”, “ShipName”, “ShipAddress”, “ShipCity”, “ShipRegion”, “ShipPostCode”, “ShipCountry”.


<asp:datagrid id="DataGrid1" runat="server" ForeColor="Black" AllowSorting="True" AllowPaging="True" GridLines="Vertical" CellPadding="3" BackColor="White" BorderWidth="1px" BorderStyle="Solid" BorderColor="#999999"  Width="100%" AutoGenerateColumns="
False">

<SelectedItemStyle Font-Bold="True" HorizontalAlign="Left" ForeColor="White"

                VerticalAlign="Top" BackColor="#000099">

</SelectedItemStyle>

                <EditItemStyle HorizontalAlign="Left" VerticalAlign="Top"></EditItemStyle>

                <AlternatingItemStyle HorizontalAlign="Left" ackColor="#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 Visible="False" DataField="OrderID" ReadOnly="True"

                HeaderText="OrderID">

</asp:BoundColumn>

                                <asp:BoundColumn Visible="False" DataField="CustomerID"                                 

                                                HeaderText="CustomerID">

</asp:BoundColumn>

                                <asp:BoundColumn Visible="False" DataField="EmployeeID"

HeaderText="EmployeeID">

</asp:BoundColumn>

                                <asp:BoundColumn DataField="ShipName" SortExpression="ShipName"

HeaderText="Name">

</asp:BoundColumn>

                                <asp:BoundColumn DataField="ShipAddress" SortExpression="ShipAddress"

                                                HeaderText="Address">

</asp:BoundColumn>

                                <asp:BoundColumn DataField="ShipCity" SortExpression="ShipCity"                   

HeaderText="City">

</asp:BoundColumn>

                                <asp:BoundColumn DataField="ShipRegion" SortExpression="ShipRegion"

                                                HeaderText="Region">

</asp:BoundColumn>

                                <asp:BoundColumn DataField="ShipPostalCode" SortExpression="ShipPostalCode"

HeaderText="Postal">

</asp:BoundColumn>

                                <asp:BoundColumn DataField="ShipCountry" SortExpression="ShipCountry"

                                                HeaderText="Country">

</asp:BoundColumn>

                </Columns>

                <PagerStyle HorizontalAlign="Center" ForeColor="Black" BackColor="#999999"

Mode="NumericPages">

</PagerStyle>

</asp:datagrid>


Screen Shots

Loading Data:

Expanding Rows:

Expanding More Rows:

Clicking on a button outside of grid on page:


Expanding Rows in a different page, and then sorting:

Clicking a button outside of datagrid where your on a a different page where sorting occurred.


The Source Code

Language used for this code is: ASP.NET, C#.  There are many tools to convert to VB.NET if needed.  The source code is very descriptive and can easily be traced.

 

Code:

 

private string connectionstring = "server=SERVERNAME;database=Northwind;uid=USERID;password=PASSWORD;";

private void Page_Load(object sender, System.EventArgs e)
{

      //Clear the contents of the Label
      this.LabelPostBack.Text = "";

      if ( !Page.IsPostBack )
      {

            BindData();  //Bind Master Details
      }
      else
      {

            for ( int i = 0; i < this.DataGrid1.Items.Count; i++ )
            {
                  //After Postback ID's get lost.  Javascript will not //work without it, so we must set them back.
                  
this.DataGrid1.Items[i].Cells[0].ID = "CellInfo" + i.ToString();
            
}

            //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.  The reason we check this, is because we 
            
//don't need to expand if it is changing the page of the 
            
//datagrid, or sorting, etc...

            if ( Request["__EVENTTARGET"] != null)
            
{
                  
string strEventTarget = Request["__EVENTTARGET"].ToString().ToLower();

                  //datagrid1 is the name of the grid.  If you modify 
                  //the grid name, make sure to modify this if 
                  //statement.

                  if ( strEventTarget.IndexOf("datagrid1") == -1)
                  
{

                     if (!Page.IsStartupScriptRegistered("ShowDataJS"))
                     
{
               
         Page.RegisterStartupScript( "ShowDataJS", "<script>ShowExpandedDivInfo('" + this.txtExpandedDivs.ClientID + "','" +
                                  this.DataGrid1.ClientID + "');</script>");
                     
}
                  
}
            }
      }
} 

private void ButtonSample_Click(object sender, System.EventArgs e)
{

      LabelPostBack.ForeColor = System.Drawing.Color.DarkRed;
      if ( txtExpandedDivs.Text.Length == 0 )
      {
         
LabelPostBack.Text = "A Postback has occurred. txtExpandedDivs has no content!";
      
}
      
else
      
{
   
      LabelPostBack.Text = "A Postback has occurred. txtExpandedDivs has contents: <BR/><B>" + 
            
this.txtExpandedDivs.Text + "</B>";
      
}
}
#region Database Methods

private void BindData()
{

      //======Query For Master Rows=======
      string QueryString = "SELECT OrderID, CustomerID, EmployeeID, 
                           
ShipName, ShipAddress, ShipCity, ShipRegion, 
                           
ShipPostalCode, ShipCountry FROM Orders";

      if ( ViewState["sortby"] != null )
      {
            QueryString = QueryString + " order by " + ViewState["sortby"].ToString();
      
}

      //==============================

      System.Data.SqlClient.SqlConnection conn = new 
            System.Data.SqlClient.SqlConnection();

try
      {
            conn.ConnectionString = connectionstring;
            if ( conn.State == System.Data.ConnectionState.Closed )
            {
                  conn.Open();
            }                       

            System.Data.SqlClient.SqlDataAdapter adapter = new 
                  
System.Data.SqlClient.SqlDataAdapter( QueryString, conn);

            DataSet ds = new DataSet();
            adapter.Fill( ds );
            DataGrid1.DataSource = ds;
            DataGrid1.DataBind();
      }
      catch( Exception ex1 )
      {
            Response.Write( "An error has occurred: " );
            Response.Write( ex1.Message.ToString() );
            Response.End();
      }
      finally
      {
            if ( conn.State == System.Data.ConnectionState.Open )
            {
                  conn.Close();
            }
      } 
} 

private DataSet RunQuery(string QueryString)
{
      System.Data.SqlClient.SqlConnection conn = new 
   
                  System.Data.SqlClient.SqlConnection();

      try
      {
            conn.ConnectionString = connectionstring;
            if ( conn.State == System.Data.ConnectionState.Closed )
            {
                  conn.Open();
            }                       

            System.Data.SqlClient.SqlDataAdapter adapter = new 
              System.Data.SqlClient.SqlDataAdapter( QueryString, conn);           

            DataSet ds = new DataSet();
            adapter.Fill( ds );
            return ds;
      }
      catch(Exception ex1)
      {
            Response.Write("An Error has occurred.<BR />");
            Response.Write(ex1.Message.ToString());
            Response.End();

            //This line below will never execute.
            return null;
      }
      finally
      {
            if ( conn.State == System.Data.ConnectionState.Open )
            {
                  conn.Close();
            }
      }
} 

#endregion

#region Datagrid Methods

private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
      //If your page size is 10, only 10 sub queries will be done.
      if ( e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem )
      { 

string DetailsQuery = "SELECT C.CompanyName, OD.UnitPrice, " +
   
"OD.Quantity, OD.Discount, E.FirstName, " + 
   "E.LastName "FROM [Order Details] as OD, " +
   
"[Customers] as C, [Orders] as O, " + 
   
"[Employees] as E " + " where OD.OrderID = " +
   
"O.OrderID and O.CustomerID = " +
   "C.CustomerID and O.EmployeeID = E.EmployeeID and " +
   "O.OrderID = '" + e.Item.Cells[1].Text + "' and " +
   
"C.CustomerID = '" + e.Item.Cells[2].Text + "' and " + 
   
"E.EmployeeID = '" + e.Item.Cells[3].Text + "'";

            //Here I am grabbing the additional data and putting it 
            //into mini datagrids...
            //If you wish to just use labels, or other controls, just 
            //bind the data as you
            
//wish, and render to html as I did.

            DataSet ds = this.RunQuery(DetailsQuery);
            DataGrid NewDg = new DataGrid();
            NewDg.AutoGenerateColumns = true;
            NewDg.Width = Unit.Percentage(100.00);
            NewDg.DataSource = ds;
            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;'>";

            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 (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() + "');  ChangePlusMinusText('" + 
   
e.Item.Cells[0].ClientID + "'); SetExpandedDIVInfo('" + 
   
e.Item.Cells[0].ClientID + "','" + this.txtExpandedDivs.ClientID + 
   
"', 'uniquename" + e.Item.ItemIndex.ToString() + "');";

            e.Item.Cells[0].Attributes["onmouseover"] = "this.style.cursor='pointer'";

            e.Item.Cells[0].Attributes["onmouseout"] =  "this.style.cursor='pointer'";
   
}
}







private
void DataGrid1_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
{
      
//clean up expanded records.
      
this.txtExpandedDivs.Text = "";
      
DataGrid1.CurrentPageIndex = e.NewPageIndex;
      
BindData();
}
 

private void DataGrid1_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{
      this.txtExpandedDivs.Text = "";
      string sortby = "[" + e.SortExpression + "]";

      if ( ViewState["sortby"] == null )
      {
            sortby = sortby + " ASC";
            ViewState["sortby"] = sortby;
            BindData();       
      }
      else
      {
            if ( ViewState["sortby"].ToString() == sortby + " ASC")
            {
                  sortby = sortby + " DESC";
                  ViewState["sortby"] = sortby;
                  BindData(); 
            }
            else if ( ViewState["sortby"].ToString() == sortby + " DESC")
            {
                  sortby = sortby + " ASC";
                  ViewState["sortby"] = sortby;
                  BindData();       
            }
            else
            {
                  sortby = sortby + " ASC";
                  ViewState["sortby"] = sortby;
                  BindData(); 
            }
      }
} 

public void SetProps(System.Web.UI.WebControls.DataGrid DG)
{
      /***************************************************************/
      DG.Font.Size = 8;
      DG.Font.Bold = false;
      DG.Font.Name = "tahoma"; 
      /*****************Professional*****************/
      //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
 

Using the code with your database

In order to use the above code, just modify three things, and your all set:

  1. In the BindData() Method, insert your master query to your database.
  2. In the DataGrid Item_DataBound Method, modify the subquery to your database.
  3. If you modified the grid name, change it in the code as well.  Just find and replace the old datagrid name: “datagrid1” to your new datagrid id.
  4. Compile, and Run!!!

 

Problems with the code

Many people complain how the run time is increased by doing the sub query.  For the next version, I plan on resolving this issue.  I don’t however find a dramatic different if you keep the page size small.  Unless you have a page size of 500 or so, you really can’t see a big difference.   Remember, the item databound fires for the amount of items in the page.  So if you page size is 500, the item databound, will fire for the 500 rows, plus header and footer, etc…

 

Complaints about the code

There are various other solutions, and this is not the only one. If you are disgusted by this code, then please do not use it.  It is complete for a learning experience, and resolved my project dilemmas.  Best of luck!

 

JavaScript Source Code

Please download the source code to get all the contents.  Thanks.

 

Copyright

The following code and be modified, and used by all users.  It may not be sold, either as whole, or part of any package without the consent of the author.

 

 

Notes

I tried to show this example using the Northwind database so you can download and run the example directly. Please modify the database tables if you do not have the Northwind database.
 

Tags

 

Ratings

Was this article helpful? Don't forget to rate it. Ratings helps community members identify top & useful articles.
Current Rating: rating starrating starrating starquarter star
Rate this article:
(1-Poor, 2-Needs Improvement, 3-Average, 4-Good, 5-Excellent)
 

Feedback

Have a question, suggestion or feedback for this article? Leave your comments below.
Share your feedback:
Need to upload images with your comment. Upload your images here: Image Shack. Remember to copy the url of your uploaded image and insert it into the comment.
You can insert images by clicking on the following icon: insert comment image
(Members Only)
 

Latest Comments

Below are the latest comments from other ProgTalk members.
Posted on:
8/25/2009 12:00:00 AM
Posted by:
thanks you so much very good site chat sohbet odalari kamerali sohbet forum
Posted on:
7/24/2009 12:00:00 AM
Posted by:
Posted on:
7/8/2009 12:00:00 AM
Posted by:
Hi ,
 The code works great .. i need a small help..can you tell me how to add my own custom headers for the child rows. In case of parent i added the code in OnRowCreated Function using if (e.Row.RowType == DataControlRowType.Header)and it works fine. But i dont kknow how to add similarly for child rows.Thanks in advance
Posted on:
6/14/2009 12:00:00 AM
Posted by:
Hi,

I like to add a SELECT column to let the user select a row.
This column is still empty but as I read here about the thread of a checkbox this problem is because of the redraw.
However if I add an empty column at the end my SELECT column will be displayed.
The select functionality of it is still given but after I select a row the expand function doesn''t work anymore.
Is there''re an way for to make it working?

Thanks,

Andre
Posted on:
6/15/2009 12:00:00 AM
Posted by:

send me a private email msg then i will send you the code: josephlapuz@gmail.com

 

Posted on:
6/4/2009 12:00:00 AM
Posted by:
do

How do I add filters to child gridview? (just for 2 columns and may need to added on runtime. I know the column names "quantity" and "expDate")

Posted on:
6/3/2009 12:00:00 AM
Posted by:
do

Rajib,

I tried to follow your link on "Expand All" but I noticed that I have 100+ uniquename(1 thru 100+). Does that mean I have to pass all of the uniquename. Very confused. Can you please post what all I need in order to implement "Expand All" including aspx.cs and aspx page. (I tried to follow other guy link ShowAll and HideAll with hlShowAll but NOOOOO luck. Please suggest.)

I would truly appreciated it. I am struglling with this for few days. Hope you understand.

Thanks
~ Do ~

======= original post ========
Posted By: Rajib
Posted Date: 12/15/2008
Message:


I think the javascript function would be:

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

You would need to pass the generic div id which is uniquename, HideShowAll(''uniquename'');
Just view the source of your aspx page using mozilla or ie, and check what your div id''s are. 
It will be something likeuniquename1, uniquename2, etc...

Posted on:
5/5/2009 12:00:00 AM
Posted by:
hi,
 i wanted to display the expended row with one column with hyperlink. so if there are 4 rows generated from the datasource query, there are 4 hyperlink in column 1. how can i do that? please help.

nice code anyway..
thanks
jo
Posted on:
12/7/2008 12:00:00 AM
Posted by:

Dear Rajib,

Regarding a comment for ShowAll and HideAlll function, your comment code is work well, except the "+" sign did not change to "-" sign in ShowAll(...) function code. Please advice of how to implement changeSign function, as I''m not familiar to Java, I get doubt on how to issue e.item.cell[0] parameter in java scrip at local site. :-(

Regards,

Prasert

Posted on:
12/7/2008 12:00:00 AM
Posted by:
I have this script somewhere.  I look for it, and post it up soon.
Posted on:
11/17/2008 12:00:00 AM
Posted by:
Thats  Good For new Users For Likely Me.
 

Posted on:
11/3/2008 12:00:00 AM
Posted by:

Hello Rajib,

can you help me on this please:

I added a column to the child grid from its dataset means at the query I added "select......,convert(0,bit) as [check]..."  now I''m having the last column of the child grid as a check box that I''ve set to enabled=true so user can check it.
Now user can check many chldren rows from many children grids and than he will click a button to update some data in the database.
So how can I get the checked rows after user have click the button outside the Master grid.

Thanks in advance

Posted on:
11/6/2008 12:00:00 AM
Posted by:

hmm....interesting scenario.  What I would suggest is to create an id for the the checkbox that is the same as the primary id of the record.  So if the row primary key in the database is 214, the checkbox id would be chk214.  So now all the checkboxes will have a unique id.  Next create a button outside the grid.  When a user clicks the button, call a javascript function that will get all checkboxes that are marked as true in the grid.  Based on all the checked checkboxes generate a parsed string such as chk214-chk215-chk216 and do a call back or postback passing this data.  In the page load, check if its a call back, and get the querystring values, and process the rows for 214, 215, 216.  Another possible way would be to create an event for the checkboxes as they are clicked.  So in the Item databound create a event for the checkbox.  this would be something like:

chk.CheckedChanged +=new EventHandler(chk_CheckedChanged);

Then just do your logic in that method.

Posted on:
11/8/2008 12:00:00 AM
Posted by:

Dear Rajiib,

This is the code I wrote in the whole page:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

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

        if (!Page.IsPostBack)
        {  
          
            BindData();
        }
        else
        {
            for (int i = 0; i < gvOrderHist.Rows.Count; i++)
            {
                //After Postback ID's get lost.  Javascript will not work without it, so we must set them back.
                this.gvOrderHist.Rows[i].Cells[0].ID = "CellInfo" + i.ToString();
            }

            //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.  The reason we check this, is because we
            //don't need to expand if it is changing the page of the
            //datagrid, or sorting, etc...

            if (Request["__EVENTTARGET"] != null)
            {
                string strEventTarget = Request["__EVENTTARGET"].ToString().ToLower();

                if (strEventTarget.IndexOf("gvorderhist") == -1)
                {

                    if (!Page.IsStartupScriptRegistered("ShowDataJS"))
                    {
                        Page.RegisterStartupScript("ShowDataJS", "<script>ShowExpandedDivInfo('" + this.txtExpandedDivs.ClientID + "','" +
                                  this.gvOrderHist.ClientID + "');</script>");
                    }
                }
            }
        }
    }
    private void BindData()
    {
        string sqlOrder = "select [order_id],[order_num],[order_date],[tajheez_num],[tajheez_date],[engdir_num],[engdir_date],[kotaa_id],[tasnif],[wasitat] from [order]";

        if (ViewState["sortby"] != null)
        {
            sqlOrder = sqlOrder + " order by " + ViewState["sortby"].ToString();
        }

        WebService wb = new WebService();
        gvOrderHist.DataSource = (DataSet)wb.GetDataSet(sqlOrder);
        gvOrderHist.DataBind();
    }
  

   
    protected void gvOrderHist_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)// || e.Row.RowType== DataControlRowType.
        {
            string sqlDetails = "SELECT od.[order_id],od.[order_details_id],od.[item_nsn],i.[status_desc],"+
                                        "l.[location_desc],m.[money_source_desc],od.[to_purchase],od.[qte_req]," +
                                        "od.[qte_locked],od.[qte_accepted],od.[qte_received],convert(bit,0) as [check] " +
                                "FROM [order_details] od,[order] o,rt_item_status i,location l,rt_money_source m "+
                                "where o.order_id=od.order_id and od.item_status=i.status_id and "+
                                   " od.location_from =l.location_id and od.money_source_id=m.money_source_id and "+
                                   "o.order_id="+e.Row.Cells[1].Text;// and od.qte_received=od.qte_accepted";

            //Creating a new GridView to show the details of this item.
            WebService wb = new WebService();
            DataSet ds = wb.GetDataSet(sqlDetails);
           
            GridView gvOrderDetails  = new GridView();
            gvOrderDetails.ID = "gvOrderDetails" + e.Row.RowIndex.ToString();

            //DataGrid gvOrderDetails = new DataGrid();
            gvOrderDetails.AutoGenerateColumns =  true;
            gvOrderDetails.Width = Unit.Percentage(100.0);
         

       
            gvOrderDetails.DataSource = ds;
            gvOrderDetails.DataBind();

        
            //Set up how the details datagrid will look like.
            SetProps(gvOrderDetails);
            //enable the check box
            if (gvOrderDetails.Rows.Count > 0)
            {
                for (int i = 0; i < gvOrderDetails.Rows.Count; i++)
                {
                    ((CheckBox)gvOrderDetails.Rows[i].Cells[11].Controls[0]).Enabled = true;
                }
            }

            System.IO.StringWriter sw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
          
            gvOrderDetails.RenderControl(htw);
           
            string DivStart = "<DIV id='uniquename" +
                  e.Row.RowIndex.ToString() + "' style='display:none'>";//'DISPLAY: none;'>";

            string DivBody = sw.ToString();
            string DivEnd = "</DIV>";
            string FullDIV = DivStart + DivBody + DivEnd;

            int LastCellPosition = e.Row.Cells.Count - 1;
            int NewCellPosition = e.Row.Cells.Count - 2;

            e.Row.Cells[0].ID = "CellInfo" + e.Row.RowIndex.ToString();
           

            if (e.Row.RowType== DataControlRowType.DataRow)
            {
                e.Row.Cells[LastCellPosition].Text = e.Row.Cells[LastCellPosition].Text +
                   "</td><tr><td bgcolor='f5f5f5'></td><td colspan='" +
                   NewCellPosition + "'>" + FullDIV;
            }
            else
            {
                e.Row.Cells[LastCellPosition].Text = e.Row.Cells[LastCellPosition].Text +
                   "</td><tr><td bgcolor='d3d3d3'></td><td colspan='" +
                   NewCellPosition + "'>" + FullDIV;
            }
           
            e.Row.Cells[0].Attributes["onmouseover"] = "this.style.cursor='pointer'";


            e.Row.Cells[0].Attributes["onmouseout"] = "this.style.cursor='pointer'";


            e.Row.Cells[0].Attributes["onclick"] = "HideShowPanel('uniquename" +
               e.Row.RowIndex.ToString() + "');ChangePlusMinusText('" +
               e.Row.Cells[0].ClientID + "'); SetExpandedDIVInfo('" +
               e.Row.Cells[0].ClientID + "','" + this.txtExpandedDivs.ClientID +
               "', 'uniquename" + e.Row.RowIndex.ToString() + "');";
        }
    }

    public void SetProps(System.Web.UI.WebControls.GridView gv)//(DataGrid gv)//
    {   
        gv.Font.Size = 8;    
        gv.Font.Bold = false;   
        gv.Font.Name = "tahoma"; 
    
        /*******************Professional 2********************/
        //Border Props
       gv.GridLines = GridLines.Both;  
        gv.CellPadding = 3; 
        gv.CellSpacing = 0;  
        gv.BorderColor = System.Drawing.Color.FromName("#CCCCCC");   
        gv.BorderWidth = System.Web.UI.WebControls.Unit.Pixel(1);  
        //Header Props
       gv.HeaderStyle.BackColor = System.Drawing.Color.SteelBlue;
       gv.HeaderStyle.ForeColor = System.Drawing.Color.White;
       gv.HeaderStyle.Font.Bold = true;
       gv.HeaderStyle.Font.Size = 8;
       gv.HeaderStyle.Font.Name = "tahoma";
       gv.RowStyle.BackColor = System.Drawing.Color.LightSteelBlue;
      // gv.ItemStyle.BackColor = System.Drawing.Color.LightSteelBlue;
    }
    protected void gvOrderHist_Sorting(object sender, GridViewSortEventArgs e)
    {
        this.txtExpandedDivs.Text = "";
        string sortby = "[" + e.SortExpression + "]";

        if (ViewState["sortby"] == null)
        {
            sortby = sortby + " ASC";
            ViewState["sortby"] = sortby;
            BindData();
        }
        else
        {
            if (ViewState["sortby"].ToString() == sortby + " ASC")
            {
                sortby = sortby + " DESC";
                ViewState["sortby"] = sortby;
                BindData();
            }
            else if (ViewState["sortby"].ToString() == sortby + " DESC")
            {
                sortby = sortby + " ASC";
                ViewState["sortby"] = sortby;
                BindData();
            }
            else
            {
                sortby = sortby + " ASC";
                ViewState["sortby"] = sortby;
                BindData();
            }
        }

    }
    protected void btnArchive_Click(object sender, EventArgs e)
    {
       
        for (int i = 0; i < gvOrderHist.Rows.Count; i++)
        {
            string gv = "gvOrderDetails" + i.ToString();

            ContentPlaceHolder cm = Master.FindControl("ContentPlaceHolder1") as ContentPlaceHolder;
            if (cm != null)
            {
                Button btn = cm.FindControl("btnArchive") as Button;
                GridView gvDetails = cm.FindControl(gv) as GridView;
                // GridView gvDetails =  FindControl(gv) as GridView;
                int RowsChecked = -1;

                if (gvDetails != null)
                {
                    for (int j = 0; j < gvDetails.Rows.Count; j++)
                    {
                        if (((CheckBox)gvDetails.Rows[j].Cells[11].Controls[0]).Checked == true)
                        {
                            RowsChecked += 1;
                            string sqlDetailsHist = "INSERT INTO [order_details_hist]([order_details_id],[order_id],[item_nsn],[item_status],[location_from],[money_source_id],[to_purchase],[qte_req],[qte_locked],[qte_accepted],[qte_received])" +
                                            " select * from order_details where order_details_id=" + gvDetails.Rows[j].Cells[1].Text;
                        }
                    }
                    if (RowsChecked == gvDetails.Rows.Count)//all details are checked so insert order hist also
                    {
                     //N.B if order has transaction we cannot delete it
                    }
                }
            }


        }
    }
}


So as you can see I'm geneating the check box from the query, plus my main problem is that I'm a little bit weak in javascript, can you please help me and indicate the code I have to write. and if there is another way to create the checkbox instead of the query it is ok for me.



I have another problem is that I'm using MasterPage inside it the scriptmanager so all the javascript functions run succesfully but I'm always getting an Unspecified error,I tried to put the code in a page without MasterPage and scriptmanager everything is going right!! Do you have any solution for this error?

Posted on:
10/24/2008 12:00:00 AM
Posted by:
Hey I''m also trying to add a child node within a child node. Let me set it up for you. We have a RD project tracker we are working on. The main Grid will be the project name, project description. The first child node will be the activity child node. What is shown in this child node is all the activities done for that project and the hours logged for it. Within that child node when you click the + on the activity you get another child node containing a username and logged hours for that activity. I would be happy to email you some source code. Email me at dhogan@gandigroup.com if you can help me.

So far I''ve got it to add a column to the current child node, it''s a hyperlink column like you have setup in the main grid. Now I''ve got the code behind to make the child node, I just don''t think it''s got the right code to pull up the child node within the child node. I''m a new programming and learning as I go, any help you can give me would be great.
Posted on:
11/6/2008 12:00:00 AM
Posted by:
Can you share some code on how you are building the child rows.  You may want to use a tree contol in the child grid. Sorry for the delay in the reply.  Didn't see this post.
Posted on:
9/9/2008 12:00:00 AM
Posted by:
Hi,
I want to add one child grid inside the child grid for that i included the ItemDataBound event for the first child grid, but it does not get fired.Can you please ehelp in this.
Posted on:
9/9/2008 12:00:00 AM
Posted by:
Hi,
I want to add one child grid inside the child grid for that i included the ItemDataBound event for the first child grid, but it does not get fired.Can you please ehelp in this.
Posted on:
9/28/2008 12:00:00 AM
Posted by:
Can you provide a little source code,  so I can see how your trying to implement this?
Posted on:
8/9/2008 12:00:00 AM
Posted by:
hi..
Could you do this code for Visual studio 2005 with Gridview...
from yesterady i am trying to make it work with gridview
and i did try to change at lot many places but i am getting few minor error becoz of javascript i think so.
as i didnt want the button and messages as i jus wanted to display the information

Thanks.
Posted on:
8/9/2008 12:00:00 AM
Posted by:
This is the solution for a gridview. http://www.progtalk.com/ViewArticle.aspx?ArticleID=54
Posted on:
8/9/2008 12:00:00 AM
Posted by:
Thanks a Lot Rajib....Will check the solution.
Thanks once again.
Posted on:
7/30/2008 12:00:00 AM
Posted by:

Rajib, great article
But is it possible to style mini grid''s columns?
As already has been said even after NewDg.DataBind()  NewDg.Columns.Count still returns 0.
How let''s say to right align a specified column or to change it''s header text?
Thanks

Posted on:
7/30/2008 12:00:00 AM
Posted by:
i created a style in my css file for a different table.  Then just gave the child grid that style.
Posted on:
7/30/2008 12:00:00 AM
Posted by:
I didn''t mean to style a child grid, just a single column
Posted on:
7/21/2008 12:00:00 AM
Posted by:
awesome article. thanks alot. and also thanks for the excellent feedback & response on the comments.
Posted on:
6/10/2008 12:00:00 AM
Posted by:
how can i expand  on page load all the datagrid . And then when you click on <A>-</A> , it will hide the datagrid chilld
Posted on:
6/10/2008 12:00:00 AM
Posted by:
You have to modify the DataGrid1_ItemDataBound method.  Change the following line:

From:     string DivStart = "<DIV id='uniquename" + e.Item.ItemIndex.ToString() +"' style='DISPLAY: none;'>";

To:         string DivStart = "<DIV id='uniquename" + e.Item.ItemIndex.ToString() +"' style='DISPLAY: block;'>";

To get all the hyperlinks to a minus (-) instead of a plus (+), go to the design mode of the grid, and look at the columns.  Simply change the plus to a minus/dash character and your all set.
Posted on:
6/5/2008 12:00:00 AM
Posted by:

is it possible to add a dropdownlist and an editable texbox in the datagrid child???
if yes can you help me please
thank you so much

Posted on:
6/5/2008 12:00:00 AM
Posted by:

This might be quite difficult to do.  You can easily put in the drop down list, and textbox, but retrieving the data after postbacks will become difficult.  Did you want them to be able to edit the child rows and save the information?  If this is the case, you are better of putting a hyperlink that will go to a edit page, and come back once they are done.

Posted on:
6/6/2008 12:00:00 AM
Posted by:

my dropdown is generate using database !!!

 is it still possible?

 and plus when my childDatagrid is appearing , i can't see all the information .
All i can see is the datagrid child header . how can i see all the information on my datagrid child cause i can find our you control your child data grid and plus i can put any breakpoint in a Javascript code.
thank you for your advices .

Posted on:
6/6/2008 12:00:00 AM
Posted by:

my dropdown is generate using database !!!

 is it still possible?

 and plus when my childDatagrid is appearing , i can't see all the information .
All i can see is the datagrid child header . how can i see all the information on my datagrid child cause i can find how you control your child data grid and plus i can put any breakpoints in a Javascript code.
thank you for your advices .

Posted on:
6/6/2008 12:00:00 AM
Posted by:
The child datagrid is being generated on the row databound method.  I think you are not seeing any rows, because the query for the child grid may be incorrect.  Check that method to first see if the child information is shown.  You can control the child datagrid in this event as well.  Let me know if you run into problems.
Posted on:
6/9/2008 12:00:00 AM
Posted by:
i have run my query with my Sql query analyzer and it returns some data but when i'm on my datagrid child, All i can see is the header.
what am i doing worng i do not understand ?
thank you
Posted on:
6/9/2008 12:00:00 AM
Posted by:

and i have added dropdownlist ,and a texbox and it works fine . i can send you the codes so you could update a new and complete DAtagrid hierarchy .

 

THANK YOU SO MUCH for a wonderful EXAMPLE !!

Posted on:
7/11/2008 12:00:00 AM
Posted by:
HI, if you have modified the code to edit the master and child row data, please post it or reply to kcnagaraju@hotmail.com? Thanks.
Posted on:
6/9/2008 12:00:00 AM
Posted by:
Does this mean the child grid info are properly showing now?  It would be great if you shared the code.  I will definately put it into an article, and share it with others for a more extendable solution.  Thanks.
Posted on:
6/1/2008 12:00:00 AM
Posted by:
ha
Rajib, many thanks for your Hgrid, it'' s really useful.
Posted on:
5/29/2008 12:00:00 AM
Posted by:
Great Article.  Exactly what I am looking to do.  Unfortunatly, I am having a hard time getting this to work with a master page.  Normally I use the controlID generated by .net, but I don''t know what it is because the div is being dynamically created.  A null value is returning from Document.getElementById(aID) instead of an object.  Any help would be appreciated.
Posted on:
5/29/2008 12:00:00 AM
Posted by:
Great Article.  Exactly what I am looking to do.  Unfortunatly, I am having a hard time getting this to work with a master page.  Normally I use the controlID generated by .net, but I don''t know what it is because the div is being dynamically created.  A null value is returning from Document.getElementById(aID) instead of an object.  Any help would be appreciated.
Posted on:
5/29/2008 12:00:00 AM
Posted by:
Great Article.  Exactly what I am looking to do.  Unfortunatly, I am having a hard time getting this to work with a master page.  Normally I use the controlID generated by .net, but I don''t know what it is because the div is being dynamically created.  A null value is returning from Document.getElementById(aID) instead of an object.  Any help would be appreciated.
Posted on:
5/29/2008 12:00:00 AM
Posted by:
I took the the entire contents of the example in this example, and created a web user control.  I placed the web user control in side a content panel of a master page, and everything seems to work from my side.  I am not getting an error on my side.
Posted on:
5/14/2008 12:00:00 AM
Posted by:

can i do this same with GRIDVIEW

Posted on:
5/14/2008 12:00:00 AM
Posted by:

There is an article for the gridview in VS2005/08 at the following URL:
http://www.progtalk.com/ViewArticle.aspx?ArticleID=54

Posted on:
4/30/2008 12:00:00 AM
Posted by:
Never mind, dumb question.

I added a empty bound column at the end (after my template column containing the checkbox) like this -

<asp:BoundField HeaderText="" HeaderStyle-Width="0"/>

 and that worked. The only drawback it adds a empty stub..I couldn''t reduce the width to nothing. If I made it invisible then the expand collapse did not work. I got javascript error - object required when I click on the ''+'' to expand. I did not dig into that as I am leaving the empty column stub. But any sugegsstions are welcome.

Posted on:
4/30/2008 12:00:00 AM
Posted by:
Thanks for the tip.  I was going through the same problem.  Who knew it would be such an easy fix.  The good part of doing it this way, is that it doesn't really affect your performance since it's only a blank column.
Posted on:
4/30/2008 12:00:00 AM
Posted by:
My previous question to above post never got posted. So I will post it again, so my above post makes sense.

The expand/collapse works great, but when my last column of the datagrid is - a template column containing a checkbox - it still works, but it overwrites my checkbox, so my checkbox is never displayed. 

In ItemDatabound event - 

e.Row.Cells[LastCellPosition].Text = e.Row.Cells[LastCellPosition].Text + "</td><tr><td bgcolor=''f5f5f5''></td><td colspan=''" + NewCellPosition + "''>" + fullDIV;

When the last column is template column - e.Row.Cells[LastCellPosition].Text - returns empty string. And above code overwrites the checkbox in the last column. But the expand collpase still works.

The resolution for this in my above post. thx

Posted on:
4/24/2008 12:00:00 AM
Posted by:
Hi Rajib
I was tried your script and run in Mozilla and IE but when I click +, it''s no run this function + for
expand/collaspe
please help me
Posted on:
4/24/2008 12:00:00 AM
Posted by:
What error message are you getting?  If you downloaded the source code it should definately work.  Only thing that needs to be changed, is the connection string to the Northwind database for the MS SQL Server.  The collapse/expand functionality is actually done through javascript. 
Let me know the error message, and I'll try to help you out.
Posted on:
4/18/2008 12:00:00 AM
Posted by:
Hi Rajib,

I am using a similar concept for displaying my data. I have an item tempklate column in the child grid. I am unable to write the itemdatabound event of the inner grid . please let me know where to write the event and how to acheive that.
 
I have writtem the follwing code in "Itemcreated" event of the parent grid

If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then

Dim dgchild As DataGrid = CType(e.Item.FindControl("dgChildgrid"), DataGrid)

dgchild.ItemDataBound += New System.Web.UI.WebControls.DataGridItemEventHandler(dgchild_ItemDataBound)         '''''' This line shows some error

End If


Your help will be very much appreciated .

Ragha
Posted on:
4/18/2008 12:00:00 AM
Posted by:
What error message are you getting?  You should also check if the childgrid is null or not before creating an event for it.  Usually you would create an event handler and then add the child grid with item templates
Posted on:
4/18/2008 12:00:00 AM
Posted by:
Hi Rajib,

Also  I want to hide the shild grid column after clicking a button on the webpage..
please let me know how should I do that.

Ragha

Posted on:
4/18/2008 12:00:00 AM
Posted by:
If you want to hide the column, try doing the following before you bind the child dataset in the itemdatabound:

if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{

    int ColumnHidePosition = 2;
    if (ds.Tables[0].Columns.Count >= ColumnHidePosition)
    {
         ds.Tables[0].Columns.RemoveAt(ColumnHidePosition);
    }
}

NewDg.DataSource = ds;
NewDg.DataBind();

Posted on:
4/16/2008 12:00:00 AM
Posted by:

A Different Approach,
Different thinking

thanks

Posted on:
4/8/2008 12:00:00 AM
Posted by:
Hi Rajib,

Great article!  Anyway, I also need editing feature. I can added Edit,Cancel,Update,Delete & Insert row into a master table and do database handle accordingly, But How to added those feature into detail table that was handled locally by javascript? Please advice.

Regards,
Posted on:
4/8/2008 12:00:00 AM
Posted by:

I see you discovered the flaw of the hgrid.  =) 
There are actually two ways of handling this.  The first way is the simple of two, but something you may not prefer.  Usually I just add a hyperlink in the child rows which passes the id to another page where they can edit the child record.

The more stylish way and second way is to use a div that is in absolute position with style attribute as:

<div id="DivChildDetails" style="display: none; visibility: visible"></div>
along with the absolute width, position, height, etc...

This way when your user clicks on edit from the child rows, do the following:
1. use some javascript to show the div ( this.style.display = "block";)
2. Load a table with all the items from the child grid (You can use javascript for this too)
3. Let them make their changes, and hit a submit button.

On the submit button you can update your record, and the current page will automatically change with the new results.

Let me know if this helps.

Posted on:
3/11/2008 12:00:00 AM
Posted by:

Hi Rajib,

I tried this solution, and it is working perfectly. But I really need 1 thing in this solution which is paging in the child grid.
May I know is there anyway to do this?

Thank you.

Wai Loon

Posted on:
3/11/2008 12:00:00 AM
Posted by:
It is definately possible to do this, but the approach you would take is a bit different.  You see, because of the way we are binding the inner child grid, it does not maintain a viewstate.  For this reason, it loses some basic functionalities such as paging and sorting.  What you can do, is have some sort of dropdownlist outside of the grid.  When a user selects an item from the drop down list, do a postback, and rebind the datagrid. 

Now when you rebind, in your item databound, you have to take into account the desired sort order, and execute the child datagrid query based on the sort order.  Pretty much, this way you can query for the child row, and order by your users desired choice.  This way it will do it for all child datarows across the entire grid.

Hope this helps.
Posted on:
3/7/2008 12:00:00 AM
Posted by:

Hi Rajib,

I tried ur instructions and the Grid is working quite well. Now I want to hide some columns from the child grid, but I not getting the columns. Could you please help me for the same.

Vijay

Posted on:
3/7/2008 12:00:00 AM
Posted by:
If you want to hide the column, try doing the following before you bind the child dataset in the itemdatabound:

if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{

    int ColumnHidePosition = 2;
    if (ds.Tables[0].Columns.Count >= ColumnHidePosition)
    {
         ds.Tables[0].Columns.RemoveAt(ColumnHidePosition);
    }
}

NewDg.DataSource = ds;
NewDg.DataBind();

Posted on:
3/7/2008 12:00:00 AM
Posted by:

Hi Rajib,

I tried this solution, but I want to just hide the column from the grid, means I cann''t delete it from the source table as I am internaly using the removed column.

vijay

Posted on:
3/5/2008 12:00:00 AM
Posted by:

Hi Rajib,

Now new script workin fine..and now its working fine on firfox too. There was an issue to change the plus minus symbol, because we are comparing <A>+</A> and its looking for <a>+<a>. So after changing the case it is working fine.

Thanks & Regards,
vijay

Posted on:
3/4/2008 12:00:00 AM
Posted by:
I followed Rajib''s instruction and was able to get Firefox and IE to work. I have not test the new attachement yet because mine is working, but try his new attachment it might work for ya.

Another question for Rajib. How can I add a check box column for the master grid. The reason for this is because I want to User to select which row they want to print.

Thanks.
Posted on:
3/4/2008 12:00:00 AM
Posted by:
Brian,

Just add a template column, and add the checkbox on the ItemTemplate of that column.  I think you have a print button, and if you do, when a user clicks it, just check which checkboxes are checked, and only display those items.  I just tried to add the checkbox button, and wanted to let you know to be careful where you add it.  The itemdatabound for the child rows may be referencing some id field, and you do not want to replace with the template column.  Try to keep the first column is the "+" column, followed by your id columns, followed by the template column, and then your regular viewable columns.

hope this helps.

Posted on:
3/3/2008 12:00:00 AM
Posted by:
Hi Rajib,
I tried to fix the probelms but its not fully removed in  Firfox as it is giving numerus problems on firfox. Few of the bugs has been fixed but now its not working on IE.
Please give me a solution.
Vijay
Posted on:
3/3/2008 12:00:00 AM
Posted by:
Hey Vijay,

I am working on a solution that will work for everyone both on mozilla and ie.  I hope to upload it within the next 24hours.  It will be in the downloadable zip file also.  Check back again soon, it may be ready.

Thanks.
Posted on:
3/4/2008 12:00:00 AM
Posted by:

Vijay,

I put up the new file which is compatible with mozilla and IE.  download it, and let me know if it works for you.

 

Posted on:
2/29/2008 12:00:00 AM
Posted by:
Hi Rajib,
I tried to fix the probelms but its not fully removed in  Firfox as it is giving numerus problems on firfox. Few of the bugs has been fixed but now its not working on IE.
Please give me a solution.
Vijay
Posted on:
2/29/2008 12:00:00 AM
Posted by:
hi,
i am currently using ur code....u gave sorting on master grid ...but is it possibel to use sorting in child grid inside master grid....
Please give me a solution.
Posted on:
3/3/2008 12:00:00 AM
Posted by:
It is definately possible to do this, but the approach you would take is a bit different.  You see, because of the way we are binding the inner child grid, it does not maintain a viewstate.  For this reason, it loses some basic functionalities such as paging and sorting.  What you can do, is have some sort of dropdownlist outside of the grid.  When a user selects an item from the drop down list, do a postback, and rebind the datagrid. 

Now when you rebind, in your item databound, you have to take into account the desired sort order, and execute the child datagrid query based on the sort order.  Pretty much, this way you can query for the child row, and order by your users desired choice.  This way it will do it for all child datarows across the entire grid.

Hope this helps.
Posted on:
2/27/2008 12:00:00 AM
Posted by:
Hi,

I could not download the code,

vijay.
Posted on:
2/27/2008 12:00:00 AM
Posted by:
Vijay,
I just tried to download it, and it worked for me.  Did you get some sort of error message?
Posted on:
2/28/2008 12:00:00 AM
Posted by:
Hi,
This grid works fine on IE, but its not functioning on firefox. Please make it workiing on firefox or give me some solution so that i can make it so.

Thanks,
 Vijay
Posted on:
2/28/2008 12:00:00 AM
Posted by:
Vijay,

Look at the comment a few lines above.  It has the solution you need.  I think Brian had the same problem which was fixed.
Posted on:
2/21/2008 12:00:00 AM
Posted by:
I added the Northwind via the VWD Database Explorer. I am using SQL Express 2005. I selected Microsoft SQL Server Database File (SqlClient) then the Northwind.mdf.

I changed the string from the default .cs file. to:
private string connectionstring = "server=localhost;database=Northwind;uid=Stone\test1;password=test1;";

I get this error below:
An error has occurred: Format of the initialization string does not conform to specification starting at index 46.

Please help . Thanks.
Posted on:
2/22/2008 12:00:00 AM
Posted by:
I finally can connect into the database. I change the SQL to mixed mode. But I am having problem on the tutorial. I was able to get the picture like the above pictures, but when I click on the sub or child grid, it gets overlapped with the parent grid below. I am using Firefox. Thanks.
Posted on:
2/22/2008 12:00:00 AM
Posted by:
I have no problem with it on IExplore from MS.
Posted on:
2/26/2008 12:00:00 AM
Posted by:
Add this function to the javascript file:

function getElement(aID)
{
    
return (document.getElementById) ? document.getElementById(aID) : getElement[aID];
}

then, in the javascript file, do a find and replace on the following:

Find:   document.all
Replace:  
getElement

This will allow IE and mozilla to work as well as other browsers as far as the javascript.

Now on your c# code, take of the Height: 1px in the Item Databound method of the datagrid. 

That should solve all your problems.
Good luck.
Posted on:
2/18/2008 12:00:00 AM
Posted by:
Jim
Here is one based on the GridView that they made into a server control.
http://www.digitaltools.com/GVT.aspx

Posted on:
2/17/2008 12:00:00 AM
Posted by:
Hi Rajb,

Just wondering if you can help on this. The example is great, but I have a little problem with adding another feature to the datagrid. I am trying to create a Build Summary with the parent as a brief description of the build and the child class as the detail description of the build. My question is that is there anyway I can separate or add a white or empty grid row for any build number(version) that is different.This should be in the parent.I am using mysql I a version column for this in the database. Thank you.

For example,

Instead of :

v2022
v2022
v2022.1

I would like it to be:

v2022
v2022
------------------
------------------
v2022.1

Posted on:
2/17/2008 12:00:00 AM
Posted by:
Brian,
I think you should look at the following article:
http://www.progtalk.com/ViewArticle.aspx?ArticleID=8

It shows how to group items of a datagrid.  Pretty much you have to bind your data, which is sorted by something, and parse through the records of the grid, and insert a new item when you see duplicates.  The link above shows how to group a sorted grid, which may be of relavance.  If this doesn''t help, let me know so I can try some things on my own.
Posted on:
2/17/2008 12:00:00 AM
Posted by:
How can you expand/collaspe all rows at once?
Posted on:
2/18/2008 12:00:00 AM
Posted by:
Brent,

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:

if ( !Page.IsPostBack )
{
      //Bind Master Details
     
BindData();
      this.HLShowAll.Attributes["onclick"] = "ShowAll(''" + this.DataGrid1.ClientID + "'');";
}

3.  Add the following function to your javascript file:

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);
    }
}

Note:  I put the counter up to 10 because the page size is 10.  If your page size is greater, or less, modify accordingly.  Let me know if this helps.

Posted on:
6/3/2009 12:00:00 AM
Posted by:
do

Brian,

Are you sure about assigning an ID with HyperlinkColumn cause HyperlinkColumn does not had ID property to it. TemplateColumn then HyperLink is the only way I see I can assign ID to it.
Also, I dont see my hyperlinkcolumn in "this" . Please suggest.

Posted on:
2/18/2008 12:00:00 AM
Posted by:
Oops, When adding the attributes to the hyperlink, there should be one single quote, instead of two single quotes.  Hope it works.
Posted on:
11/25/2008 12:00:00 AM
Posted by:

Dear Rajib,

Yes, your comment code is work well, except the "+" sign did not change to "-" sign in ShowAll(...) function code. Please advice of how to implement changeSign function, as I'm not familiar to Java, I get doubt on how to issue e.item.cell[0] parameter in java scrip at local site. :-(

Regards,

Prasert

Posted on:
2/17/2008 12:00:00 AM
Posted by:
Brent,

Check the javascript file.  There are some functions there which expand and collapse when the users click the plus sign.  Pretty much, you can just write a for loop, which will parse through the first to last item, and expand each row.  Did you already try to create a javascript method?  On your page, if you see the datasource, you will notice that the row or div id''s are in a pattern.  look for the:  this.DataGrid1.ClientID generated on the server side code.  they usually are like:
uniquename0
uniquename1
uniquename2
etc...

You can then just call some js function which will expand all the rows.
Posted on:
1/2/2008 12:00:00 AM
Posted by:
I hope this is helpful to you guys.