[RESOLVED] [2008] - Datagridview to multidimensional array
Hello
I need some advice to accomplish this, i have a datagridview with this data:
Column1 Column2
item1 3
item2 1
item1 2
item1 5
item2 3
item3 1
item1 3
I need an array with distinct values of column1 and the sum of the values in the second dimension of the array:
ar(item1,13), ar(item2,4),ar(item3,1).
I don't know how many items i will have, so i don't know the correct dimension of the array...
I have a lot of code to do the job, but i think there is a better way...
Thanks
Re: [2008] - Datagridview to multidimensional array
Is there a datatable bound to the source of the datagridview?
If so, you can run sql like commands against it.
i.e
Code:
Dim dt As New DataTable
Dim col1Sum As Integer = dt.Compute("SUM(DISTINCT Column1)", "")
Re: [2008] - Datagridview to multidimensional array
Re: [2008] - Datagridview to multidimensional array
Well, I don't think you really do want a 2D array, or at least you shouldn't. There are some, but very few, situations where 2D arrays are appropriate. They should only be used when every element is a peer. If one column represents something completely different to another column, as is the case here, the a 2D array is completely inappropriate.
One appropriate solution would be to use a Dictionary:
vb.net Code:
Dim itemSums As New Dictionary(Of String, Integer)
Dim item As String
For Each row As DataGridViewRow In Me.DataGridView1.Rows
item = CStr(row.Cells(0).Value)
If itemSums.ContainsKey(item) Then
'Add the new value to the current subtotal.
itemSums(item) += CInt(row.Cells(1).Value)
Else
'Add the item and the first value.
itemSums.Add(item, CInt(row.Cells(1).Value))
End If
Next
Another option would be to define a type that represents an item and its corresponding value and to put instances of that type in a simple collection. In both cases you're covered for the unknown number of items because collections can grow dynamically.
If you really must use a 2D array, like if this is a poor learning exercise, then you can create the array from the collection, because at that point you know how many elements you need.
Re: [2008] - Datagridview to multidimensional array
THanks again :)
I was looking for a code similar to that a long time...
Solved