Solved

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

Posted on 2014-02-14
17
1,407 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
  • 9
  • 5
  • 2
17 Comments
 
LVL 11

Expert Comment

by:Technodweeb
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:Technodweeb
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
 

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
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 

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 Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

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

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

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now