Connecting Tech Pros Worldwide Forums | Help | Site Map

Using a GridView to display multiple sub items

Newbie
 
Join Date: Jun 2009
Posts: 3
#1: Jun 29 '09
Hello ,
I'm a beginner in visual studio 2008 using c# language

I Have this task that I seem to be stuck in !

I've created a database using sql server express 2005 of 4 tables :"BOOKS , AUTHORS , CATEGORIES and PUBLISHERS ".

I've connected this database to my gridview in visual studio , it shows me all the books like this : " BOOK publisher , TITLE, CATEGORY "

the problem is that my task is to show what every author has in terms of books .
and I cant figure out how to do that !!!!

can u tell me if any of this code that I'm using is helpfull or not ???

if it is what's missing ???????????????????


Expand|Select|Wrap|Line Numbers
  1. public partial class _Default : System.Web.UI.Page 
  2. {
  3.     protected void Page_Load(object sender, EventArgs e)
  4.     {
  5.         string ConnectionString = "Data Source=-------;Initial Catalog=boyslik;Integrated Security=True";
  6.         string selectSQL = "SELECT  [AUTHORID] FROM [AUTHORS] ";
  7.         Console.WriteLine("AUTHOR ID"  );
  8.  
  9.     }
  10.     protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
  11.     {
  12.          if (!this.IsPostBack)
  13.         {
  14.  
  15.  
  16.             string ConnectionString ="Data Source=----------;Initial Catalog=boyslik;Integrated Security=True";
  17.             string selectSQL = "SELECT [category], [title], [publisher] FROM [books JOIN AUTHORS] ORDER BY [title], [category], [publisher]" GROUP BY  author name;
  18.  
  19.  
  20.  
  21.             System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("boyslikCS");
  22.             System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(selectSQL, con);
  23.             System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter(cmd);
  24.             DataSet ds = new DataSet();
  25.  
  26.             adapter.Fill(ds, "BOOKS ");
  27.  
  28.             GridView1.DataSource = ds;
  29.             GridView1.DataBind();
  30.         }
  31.     }
  32. }
Newbie
 
Join Date: Apr 2009
Posts: 7
#2: Jun 29 '09

re: Using a GridView to display multiple sub items


Hi

Your grouping is not right like this.
What you want to do is to just list out your query without doing any grouping.

Here is an article wich might help

http://aspalliance.com/1268_CodeSnip...ew_Control.all
Frinavale's Avatar
Site Moderator
 
Join Date: Oct 2006
Location: The Great White North
Posts: 5,083
#3: Jun 29 '09

re: Using a GridView to display multiple sub items


Hi Boyslik,

You cannot use a DataSet as a DataSource for a GridView. A DataSet could possibly contain more than one table and a GridView is designed in such a way to only display one table.

Your application requires that you display data from two tables....and the GridView control does not do this by default.

To display the data you need to display a table (with book information) within a table row (representing an author)....so, in your case, you're going to require a GridView (or Repeater) (for the book information) to be displayed with a GridView Row (displaying the author information).

Here's a simple example of how to do it (sorry it's using VB.NET). The example includes JavaScript that is used to expand the details section (the books section). I was using an example based on what someone else needed help with to form an answer for you and this is why you got some JavaScript "niceties" added to your answer. You don't have to keep it if you don't want to.

ASPX code:
Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head runat="server">
  4.     <title></title>
  5.  
  6.     <script type="text/javascript">
  7.         function ExpandCollapse(detailsSectionID) {
  8.             var detailsSection = document.getElementById(detailsSectionID);
  9.             if (detailsSection) {
  10.                 if (detailsSection.style.display == "none") {
  11.                     detailsSection.style.display = "block";
  12.                 } else {
  13.                     detailsSection.style.display = "none";
  14.                 }
  15.             }
  16.         }
  17.         function ExpandAll() {
  18.             var allDivElements = document.getElementsByTagName("div");
  19.             var numElements = allDivElements.length;
  20.  
  21.             var pattern = new RegExp("ItemDetails")
  22.             for (var i = 0; i < numElements; i++) {
  23.                 if (pattern.test(allDivElements[i].id)) {
  24.                     allDivElements[i].style.display = "block";
  25.                 }
  26.             }
  27.  
  28.         }
  29.  
  30.         function CollapseAll() {
  31.             var allDivElements = document.getElementsByTagName("div");
  32.             var numElements = allDivElements.length;
  33.  
  34.             var pattern = new RegExp("ItemDetails")
  35.             for (var i = 0; i < numElements; i++) {
  36.                 if (pattern.test(allDivElements[i].id)) {
  37.                     allDivElements[i].style.display = "none";
  38.                 }
  39.             }
  40.  
  41.         }    
  42.     </script>
  43.  
  44. </head>
  45. <body>
  46.     <form id="form1" runat="server">
  47.     <asp:ScriptManager ID="SM" runat="server">
  48.     </asp:ScriptManager>
  49.     <div>
  50.         <input type="button" id="expandAll" runat="server" onclick="ExpandAll();" value="Expand All" />
  51.         <input type="button" id="collapseAll" runat="server" onclick="CollapseAll();" value="Collapse All" />
  52.         <asp:GridView ID="ItemsGrid" runat="server" AutoGenerateColumns="false">
  53.             <Columns>
  54.                 <asp:TemplateField HeaderText="Expand Details">
  55.                     <ItemTemplate>
  56.                         <asp:HyperLink ID="ExpandCollapse" runat="server" Text="+/-"></asp:HyperLink>
  57.                     </ItemTemplate>
  58.                 </asp:TemplateField>
  59.                 <asp:TemplateField HeaderText="Items">
  60.                     <ItemTemplate>
  61.                         <div style="width: 100%; text-align: center">
  62.                             <%#Eval("authorName")%></div>
  63.                         <asp:Panel ID="ItemDetails" runat="server" Style="display: none;">
  64.                             <asp:GridView ID="SubGridView" runat="server" AutoGenerateColumns="false">
  65.                                 <Columns>
  66.                                     <asp:BoundField DataField="authorID" HeaderText="authorID" />
  67.                                     <asp:BoundField DataField="bookName" HeaderText="bookName" />
  68.                                 </Columns>
  69.                             </asp:GridView>
  70.                         </asp:Panel>
  71.                     </ItemTemplate>
  72.                 </asp:TemplateField>
  73.             </Columns>
  74.         </asp:GridView>
  75.     </div>
  76.     </form>
  77. </body>
  78. </html>

VB.NET Code:
Expand|Select|Wrap|Line Numbers
  1.     Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  2.  
  3.    'Since I don't have a database to connect to....
  4.    'Here I'm creating 2 tables: one to represent the Authors,
  5.    'and one to represent the author's books.
  6.    'These two tables are related: on the Author's ID 
  7.    '(the primary key for the authors table)
  8.  
  9.         Dim authorTable As New DataTable
  10.         authorTable.Columns.Add("authorID") 'Primary key for author's table
  11.         authorTable.Columns.Add("authorName")
  12.  
  13.  
  14.         Dim booksTable As New DataTable
  15.         booksTable.Columns.Add("bookName")
  16.         booksTable.Columns.Add("authorID") 'Foriegn key
  17.  
  18.     'Here I'm populating the Authors table and the table that holds the Books
  19.     'I'm doing in such a way that each author will have 2 books
  20.         For i As Integer = 0 To 5
  21.  
  22.             Dim authorTableDR As DataRow
  23.             authorTableDR = authorTable.NewRow
  24.             authorTableDR("authorName") = "author" + i.ToString
  25.             authorTableDR("authorID") = "authorID" + i.ToString
  26.             authorTable.Rows.Add(authorTableDR)
  27.  
  28.             Dim booksTableDr As DataRow
  29.             booksTableDr = booksTable.NewRow
  30.             booksTableDr("authorID") = "authorID" + i.ToString
  31.             booksTableDr("bookName") = "bookName" + i.ToString
  32.  
  33.             Dim booksTableDr2 As DataRow
  34.             booksTableDr2 = booksTable.NewRow
  35.             booksTableDr2("authorID") = "authorID" + i.ToString
  36.             booksTableDr2("bookName") = "bookName" + i.ToString + "a"
  37.  
  38.             booksTable.Rows.Add(booksTableDr)
  39.             booksTable.Rows.Add(booksTableDr2)
  40.         Next
  41.  
  42.     'Here I'm defining the relationship between the two tables
  43.  
  44.         Dim Parent_PKColumns(0) As DataColumn
  45.         Parent_PKColumns(0) = authorTable.Columns("authorID")
  46.         authorTable.PrimaryKey = Parent_PKColumns
  47.  
  48.         Dim Child_FKColumns(0) As DataColumn
  49.         Child_FKColumns(0) = booksTable.Columns("authorID")
  50.  
  51.    'I'm adding the tables to a DataSet
  52.         Dim ds As New DataSet
  53.         ds.Tables.Add(authorTable)
  54.         ds.Tables.Add(booksTable)
  55.  
  56.    'I'm naming the relationship between the two tables so that 
  57.    'I can access it later
  58.         ds.Relations.Add("ParentChild", Parent_PKColumns, Child_FKColumns)
  59.    'I'm setting the main GridView to the Authors Table in the DataSet
  60.    'and I'm binding the GridView to the data.
  61.         ItemsGrid.DataSource = ds.Tables(0)
  62.         ItemsGrid.DataBind()
  63.     End Sub
  64.  
  65.     Private Sub ItemsGrid_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles ItemsGrid.RowDataBound
  66.  
  67.    'The following is used to apply the JavaScript responsible
  68.    'expanding details
  69.         Dim expandCollapseLink As HyperLink = CType(e.Row.FindControl("ExpandCollapse"), HyperLink)
  70.         Dim detailsSection As Panel = CType(e.Row.FindControl("ItemDetails"), Panel)
  71.         If expandCollapseLink IsNot Nothing AndAlso detailsSection IsNot Nothing Then
  72.             expandCollapseLink.Attributes.Add("onclick", "ExpandCollapse('" + detailsSection.ClientID + "');")
  73.         End If
  74.  
  75.     'Ok this is important to you: I'm retrieving the child GridView used
  76.     'to display the author's books information
  77.         Dim subGridView = CType(e.Row.FindControl("SubGridView"), GridView)
  78.  
  79.     'If I was able to retrieve the GridView, then I'm binding it to a
  80.     'child view created based on the relationship I defined above.
  81.         If subGridView IsNot Nothing Then
  82.             subGridView.DataSource = CType(e.Row.DataItem, DataRowView).CreateChildView("ParentChild")
  83.             subGridView.DataBind()
  84.         End If
  85.  
  86.     End Sub

If you have any questions feel free to ask....but before you say "I need an answer in C#" try opening a new project (VB.NET), add this code, step through it, and read my comments to try understand what I'm doing.

-Frinny
Reply