Solved

Help with grouping data in DataGridView (VS2010) using VB.NET

Posted on 2014-02-14
17
1,902 Views
Last Modified: 2016-06-20
Hi,

My DatagridView displays data in the following format:


Chapter   section    Item   Country
104        10411     abc    BEL
104        10421     def    CAN
104        10431     ghi    BEL
104        10441     jkl    BEL
105        10411     mno    BEL
105        10421     pqr    CAN
106        10431     stu    BEL
107        10441     vwx    BEL

How do I group the data by chapter, section and country and have the capability to drill down
from chapter to the other sections?

Thanks,

Victor
0
Comment
Question by:vcharles
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 9
  • 5
  • 2
17 Comments
 
LVL 11

Expert Comment

by:Gregory Miller
ID: 39859329
I would break this into two parts.
   1. How to sort data in datagrid
   2. How to group and drill down

I am making an assumption that your data is coming from a SQL DB of some sort...

1. The easiest way to do this is in your initial query by adding sort options there as such:
"SELECT 'Chapter', 'Section', 'Item', 'Country' FROM dbDataSource ORDER BY Chapter;"

2. To group gets a little bit more difficult but this is the direction I would go. Use the following query:
"SELECT DISTINT 'Chapter' FROM dbDataSource ORDER BY Chapter;"
From here you would use a click event to issue a new query to your database based on the content of the column and row of the 'Chapter' value. This query would change to something like this:
"SELECT DISTINCT 'Chapter', 'Section' FROM dbDataSource ORDER BY 'Section' WHERE 'Chapter'="value from click event"
From here, repeat the process adding to the query as required for as deep as you want to drill down...
0
 

Author Comment

by:vcharles
ID: 39859802
Hi,

I'm using the code below to display the data from a datatable, can it be modified to achieve the same.

Dim SearchCriteria As String = "LinkAID <> -1"

        If TextBoxF.Text <> "" Then
            SearchCriteria &= " AND CHPT IN (" & TextBoxF.Text & " )"
        End If

        If TextBoxG.Text <> "" Then
            SearchCriteria &= " AND SEC IN (" & TextBoxG.Text & " )"
        End If

If TextBoxC.Text <> "" Then
            SearchCriteria &= " AND CTRY IN (" & TextBoxC.Text & " )"
        End If

Dim FilteredDT As DataTable
        Dim DV As New DataView(dtsetlink.Tables(0), SearchCriteria, Nothing, DataViewRowState.CurrentRows)
        FilteredDT = DV.ToTable

        If FilteredDT.Rows.Count > 0 Then
           

            DataGrid1.DataSource = FilteredDT

Thanks,

V.
0
 
LVL 11

Expert Comment

by:Gregory Miller
ID: 39859892
I am not able to work with what you have provided here. Too many variables that mean nothing without seeing more of the code/project.
0
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 

Author Comment

by:vcharles
ID: 39860777
Can the grouping be done using Grid's properties? Most relevant part of the code is listed below. if textbox contains '104','105' the result returned from Searchcriteria would for example look like:

LinkAID <> -1" AND CHPT IN ('104','105')

Dim FilteredDT As DataTable
        Dim DV As New DataView(dtsetlink.Tables(0), SearchCriteria, Nothing, DataViewRowState.CurrentRows)
        FilteredDT = DV.ToTable

        If FilteredDT.Rows.Count > 0 Then
            DataGrid1.DataSource = FilteredDT
        End if
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 39861454
You can use LINQ to Datatable. Example code below

Dim dTable As New DataTable()
dTable.Columns.Add("id", GetType(Integer))
dTable.Columns.Add("name", GetType(String))
dTable.Rows.Add(1, "hiren")
dTable.Rows.Add(2, "solanki")
dTable.Rows.Add(3, "hiren")
Dim query = From grp In From row In dTable.AsEnumerable()Group row By row.Field(Of String)("name")New With { _
	Key .Id = grp.Key, _
	Key .sum = grp.Sum(Function(r) r.Field(Of Integer)("id")) _
}
For Each grp As var In query
	Response.Write([String].Format("The Sum of '{0}' is {1}", grp.Id, grp.sum))
Next

Open in new window

0
 

Author Comment

by:vcharles
ID: 39866205
Hi,

Can you please send me the solution in VB.NET, I'm trying to use the code below but the code is in C#. Also how do integrate the code with my code, I'm only trying to see the grid display the data in Group format. when I will need to group by multiple columns.

Dim SearchCriteria As String = "LinkAID <> -1"
        Dim FilteredDT As DataTable
        Dim DV As New DataView(dtsetLinkBEL.Tables(0), SearchCriteria, Nothing, DataViewRowState.CurrentRows)
        FilteredDT = DV.ToTable
        If FilteredDT.Rows.Count > 0 Then
            DataGridView2.DataSource = FilteredDT
        End If

    Dim query = From grp In From row In dTable.AsEnumerable()Group row By row.Field(Of String)("SN") New With { _
      Key .Id = grp.Key, _
      Key .sum = grp.Sum(Function(r) r.Field(Of Integer)("id")) _}
        For Each grp As var In query
            Response.Write([String].Format("The Sum of '{0}' is {1}", grp.Id, grp.sum))
        Next

Thanks,

Victor
0
 
LVL 83

Accepted Solution

by:
CodeCruiser earned 500 total points
ID: 39870468
I am not very good with LINQ queries so I created a test project to test the above query. I had to make a few modifications and following is what worked in the end

        Dim dTable As New DataTable
        dTable.Columns.Add("ID", GetType(Integer))
        dTable.Columns.Add("Name", GetType(String))
        dTable.Columns.Add("City", GetType(String))
        dTable.Rows.Add(New Object() {1, "Name1", "City1"})
        dTable.Rows.Add(New Object() {2, "Name2", "City2"})
        dTable.Rows.Add(New Object() {3, "Name3", "City1"})
        DataGridView1.DataSource = dTable

        Dim query = From row In dTable.AsEnumerable() Group row By City = row.Field(Of String)("City") Into CityGroup = Group Select New With {Key City, Key .Count = CityGroup.Count(Function(r) r.Field(Of Integer)("id"))}
        For Each q In query
            MessageBox.Show("City: " & q.City & ", Count: " & q.Count)
        Next

Open in new window



I encourage you to play around with this query to see how much of your requirement you are able to achieve.
0
 

Author Comment

by:vcharles
ID: 39870505
I will try it and get back to you.

Thanks.

V.
0
 

Author Comment

by:vcharles
ID: 39882755
Hi,

I'm trying to integrate your code with the code below but can't figure out, can you please help me figure it out how to sort by country and nsc.

 Dim FilteredDTA As DataTable
        Dim DVA As New DataView(dtsetLinkAOP5.Tables(0), SearchCriteria, Nothing, DataViewRowState.CurrentRows)
        FilteredDTA = DVA.ToTable
        If FilteredDTA.Rows.Count > 0 Then

            Me.C1Screen3.DataSource = FilteredDTA.DefaultView.ToTable(True, New String() {"COUNTRY", "NSC", "NAS", "QUANTITY", "PC"})


            'Dim query = From row In FilteredDTA.AsEnumerable() Group row By Country = row.Field(Of String)("Country") Into CityGroup = Group Select New With {Key City, Key .Count = CityGroup.Count(Function(r) r.Field(Of Integer)("id"))}


        Else
            Me.C1Screen3.DataSource = Nothing
            Exit Sub
        End If

Thanks,

V.
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 39885325
Sort after the grouping?
0
 

Author Comment

by:vcharles
ID: 39885479
After sorting the data in the table, is it possible to Group the data so users can choose which country they want more information on? For example, if the Grid contains a row with BEL, I would like to click on it and display the other columns with data for BEL.

I am trying to group by SN (10411,10412,10413) and when I click on 10411 see a list of countries and When I click on Countries see other columns.

Victor
0
 
LVL 83

Assisted Solution

by:CodeCruiser
CodeCruiser earned 500 total points
ID: 39885916
An easier way would be to just use the ToTable function like below


Dim dTable As DataTable = existingTable.DefaultView.ToTable(True, New String(){ "Country" })

and similarly

Dim dTable As DataTable = existingTable.DefaultView.ToTable(True, New String(){ "SN" })
0
 

Author Comment

by:vcharles
ID: 39885945
Thanks, will try it an get back to you.
0
 

Author Comment

by:vcharles
ID: 39915926
Hi,

Sorry for the late reply.

I tried the code below


        Dim dTable As DataTable = C1Screen3.DefaultView.ToTable(True, New String() {"Country"})

But received error message:

DefaultView is not a member System.Windows.Forms.DatagridView

V.
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 39940196
You need to do this on datatable not datagridview
0
 

Author Comment

by:vcharles
ID: 39984769
Sorry for the late reply. I got side track with other issues, will test it and get back to you by the end of the week.

Thanks,

Victor
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question