0

For example I have a datagridview1 with data imported from a text file and there are 3 columns: ID, Subject, Grade.

What I want to do is to Group By the ID Column and put it in a ListBox.

I dont have any database here so I can't use sql queries or is there a way to manipulate datagridview using sql queries? Just like this:

SELECT ID FROM DataGridView1 Group By ID

Any response would really be appreciated.

Kristijan Iliev
  • 4,901
  • 10
  • 28
  • 47
gilbert
  • 3
  • 1
  • 7
  • http://stackoverflow.com/questions/7325278/group-by-in-linq and https://msdn.microsoft.com/en-us/library/bb531412.aspx – Bjørn-Roger Kringsjå Aug 23 '15 at 12:36
  • If your data only exists in the DGV rather than something like a List or DataTable, it will be harder to filter, sort and group the data. Design your app around the data not the UI controls. If the data file is a CSV it is pretty simple to import it to a DataTable – Ňɏssa Pøngjǣrdenlarp Aug 23 '15 at 12:50

1 Answers1

0

You can't directly use SQL queries, but using LINQ it is possible to query data in a similar way.
The following code gets all IDs into a ListBox (as if you had used the SQL statement SELECT ID FROM DataGridView1 Group By ID):

    For Each v As String In
        From row
        In DataGridView1.Rows
        Group By val = DirectCast(row, DataGridViewRow).Cells("ID").Value
        Into Group
        Where val IsNot Nothing
        Select str = val.ToString

        ListBox1.Items.Add(v)
    Next
Zepporle
  • 413
  • 4
  • 13
  • that's exactly what i want, thank you so much but there is error when executing that code. error says "Object reference not set to an instance of an object." which the highlight is in the "val.ToString" – gilbert Aug 29 '15 at 16:15
  • Which version of Visual Studio / .NET Framework are you using? With VS2013 / .NET 4.5 it's working without an error. You could also try to remove the `.ToString` from the affected line and see if it works then. – Zepporle Aug 29 '15 at 16:42
  • tried to remove that and it has an error "Items collection cannot be modified when the DataSource property is set." – gilbert Aug 29 '15 at 16:56
  • You did't set by any chance a DataSource for the ListBox, did you? – Zepporle Aug 29 '15 at 17:05
  • i don't know how to. i'm sorry. I'm just a beginner in vb.net – gilbert Aug 29 '15 at 17:14
  • Look at the designer view of your form and select ListBox1. In the properties window (press F4 if it isn't visible) there is an entry labled "DataSource". Its value _should_ be set to sth. like 'none'... And btw. which version of Visual Studio are you using? – Zepporle Aug 29 '15 at 17:25
  • I've edited my answer to prevent empty rows from being taken into account as well. This should solve your first issue (the null reference exception). – Zepporle Aug 29 '15 at 17:35
  • oh God, thank you so much. that solved the issue. million thanks :) – gilbert Aug 29 '15 at 17:57