VB.NET Error Populating 2d Array with database field - vb.net

i have a query that contains field "kode_brg"
i want to fill them into array2d, i'm using mysqldatareader to fill the field into array2d, but it seems that the datareader only read once inside the while looping
for more specific, i've added the ss of myproblem belom
i'm pretty sure that i've made a mistake in using the nested for inside the while loop
could somebody help me fix this problem
thanks before
regards, me
EDITED: ADDED A CODE TO A QUESTIONS
'FILL X
Dim nil_x As String = "SELECT max( kode_faktur ) FROM detail"
Dim x As Int32
Dim CMD_X = New MySqlCommand(nil_x, conn.konek)
x = Convert.ToInt32(CMD_X.ExecuteScalar())
'FILL Y
Dim nil_y As String = "select max(x.jumlah) from (select count(*) as jumlah from detail group by kode_faktur)x"
Dim y As Int32
CMD_Y = New MySqlCommand(nil_y, conn.konek)
y = Convert.ToInt32(CMD_Y.ExecuteScalar())
'LOOPING ARRAY TRANS
Dim msql As String = "select kode_brg from detail group by kode_faktur"
Dim i, j As Integer
Dim arayT(,) As String
CMD = New MySqlCommand(msql, conn.konek)
'Try
Dim hasil As MySqlDataReader
hasil = CMD.ExecuteReader()
While hasil.Read()
For i = 0 To x
ReDim Preserve arayT(x, y)
For j = 0 To y
arayT(i, j) = hasil("kode_brg")
'Continue For
Next j
j += 1
'Continue For
Next i
i += 1
Exit While
End While
conn.konek.Close()
dgv2.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.EnableResizing
dgv2.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders
dgv2.RowHeadersVisible = False
With Me.dgv2
.DataSource = New Mommo.Data.ArrayDataView(arayT)
.SelectionMode = DataGridViewSelectionMode.FullRowSelect
.AllowUserToAddRows = False
.RowHeadersVisible = True
End With
one big note from me
DON'T SUGGEST ME TO USE ARRAYLIST/LIST OF/LINQ/DATASET/DATATABLE
because what i really want to do is filling the 2d array with database field, comparing it with another 1d array, then create a new 2d array from both of them, finally i want to display the newly 2d array into the grid.. that's why i chose 2d array instead using dataset to fill my grid
i don't know how to compare list(of) or arraylist with 1d array, that's why i'm using 2d array (basic)
thanks you before :)
the desired output

Assuming you managed to get array size exactly the same as number of data returned from query, you can try to change the loop to following :
ReDim Preserve arayT(x, y)
For i = 0 To (x-1)
For j = 0 To (y-1)
hasil.Read()
arayT(i, j) = hasil("kode_brg")
'Continue For
Next j
'Continue For
Next i

I have no idea of what you're trying to accomplish, but this is how you should do it:
Dim list As New List(Of String(,))
While hasil.Read()
Dim item(,) As String = New String((x - 1), (y - 1)) {}
Dim value As String = hasil("kode_brg")
For i As Integer = 0 To (x - 1)
For j As Integer = 0 To (y - 1)
item(i, j) = value
Next
Next
list.Add(item)
End While

Related

Doubles will not output in DataGridView

I have a DataGridView that I want to fill with values that are Doubles. The DataGridView filled fine when the values were strings, but now it outputs System.Double[] in the first column and nothing in any other column. I know the conversion is working because I can print the double values to the console. How do I format all columns programmatically? (I don't want to use the designer)
My code:
Dim cols() as String = {"col1", "col2", "col3"} ' this goes on for 33 cols
Dim currentRow As String()
Dim row() As Double
Dim c As Integer
DataGridView1.Rows.Clear()
DataGridView1.ReadOnly = True
DataGridView1.DefaultCellStyle.Format = "G"
DataGridView1.ColumnCount = 33
For c = 0 To (cols.Length - 1)
DataGridView1.Columns(c).Name = cols(c)
Next
While Not at EndOfFile ' This line and the next are semi-pseudocode, but it's the same idea
read/parse line into currentRow
Dim x As Integer
For x = 0 To (currentRow.Length - 1)
ReDim Preserve row(x)
Double.TryParse(currentRow(x), row(x))
Next
With Me.DataGridView1.Rows
.Add(row)
End With
Screenshot of the output:
You can first add the row to the grid, then loop through your array to add the information to each cell.
Dim i as integer = DataGridView1.Rows.Add
For x As Integer = 0 to row.Count - 1
DataGridView1.Rows(i).Cells(x).Value = row(x)
Next

I want to align Dynamic pictureboxs with Dynamic Labels

Here is my function that allows me to get from a webpage the image link for my PictureBoxs and the title for my labels
Public Shared Function getPics(website As String, pattern As String)
Dim tempTitles As New List(Of String)()
Dim tempTitles2 As New List(Of String)()
Dim lestitres As New List(Of titlesclass)
Dim webClient As New WebClient()
webClient.Headers.Add("user-agent", "null")
Dim counter As Integer = 0
Dim counter2 As Integer = 0
Dim counter3 As Integer = 0
Dim counter4 As Integer = 1
Dim counter5 As Integer = 0
Dim counter6 As Integer = 0
'If the website happens to go offline, at least your application wont crash.
Dim content As String = webClient.DownloadString(website)
Dim query = From title In Regex.Matches(content, pattern).Cast(Of Match)
Select New With {Key .Link = String.Concat("http://www.gamestop.com", title.Groups("Data").Value),
Key .Title = title.Groups("Dataa").Value}
For Each letitre In query.Distinct
'MsgBox(letitre.Link & " ======= " & letitre.Title)
Next
'For Each title As Match In (New Regex(pattern).Matches(content)) 'Since you are only pulling a few strings, I thought a regex would be better.
' Dim letitre As New titlesclass
' letitre.Link = title.Groups("Data").Value
' letitre.Title = title.Groups("Dataa").Value
' lestitres.Add(letitre)
' 'tempTitles2.Add(title.Groups("Dataa").Value)
'Next
Dim titles = tempTitles.Distinct().ToArray() 'remove duplicate titles
'Dim titles2 = tempTitles2.Distinct().ToArray()
Dim titles2 = lestitres.Distinct().ToArray()
lestitres.Clear()
'For Each title As titlesclass In titles2
For Each letitre In query.Distinct
'ListBox.Items.Add(title) 'what you do with the values from here is up to you.
Dim ImageInBytes() As Byte = webClient.DownloadData(letitre.Link)
Dim ImageStream As New IO.MemoryStream(ImageInBytes)
Dim MyPic As New PictureBox
Dim MyLab As New Label
If (counter2 > 0 AndAlso ((counter2 Mod 4 = 0) OrElse counter3 = 1)) Then
counter3 = 1
counter4 += 1
If (counter2 Mod 4 = 0) Then
counter5 = 0
counter6 += 170
End If
MyPic.Location = New Point(counter5, MyPic.Location.Y + counter6)
MyLab.Location = New Point(counter5, MyPic.Location.Y + counter6)
If counter4 = 4 Then
counter3 = 0
End If
counter5 += 200
Else
MyPic.Location = New Point(counter, MyPic.Location.Y)
MyLab.Location = New Point(counter, MyPic.Location.Y)
End If
counter += 200
counter2 += 1
MyPic.SizeMode = PictureBoxSizeMode.AutoSize
MyLab.Text = letitre.Title
MyPic.Image = New System.Drawing.Bitmap(ImageStream)
Form2.Controls.Add(MyPic)
Form2.Controls.Add(MyLab)
Next
End Function
The class named titlesclass contain two elements which i will store my Link and Title in :
Public Class titlesclass
Public Property Link As String
Public Property Title As String
End Class
And My little button does all the work
Dim websiteURL1 As String = "http://www.gamestop.com/collection/upcoming-video-games"
Class1.getPics(websiteURL1, "<img src=""(?<Data>[^>]*)""><p>(?<Dataa>[^>]*)<br>")
What i'm trying to do is to show 4 pictureboxs per row with the lables right bellow each picture , for now some labels doesn't show , some shows just in the right place and some shows very far bellow ! I tested the values i'm getting with a Message Box and it shows me the informations in the order i need , i'm not sure if i screw up in the x,y values or if it's something else ...
Edit : I can already show the 4 pictureboxes per row , the labels also , but the Y of some labels isn't well adjusted it can go far far bellow !
Here is some pictures that will help you to understand my situation Don't mind the buttons and listboxs , it's just for the test :
My list containt a lot of pictures , so i just showed you some when the thing work kind of well , when it shows couple of rows far from the designed picture
http://img110.xooimage.com/files/f/a/d/picture1-5239f7c.png
http://img110.xooimage.com/files/8/f/8/picture-2-5239f7e.png
http://img110.xooimage.com/files/4/7/b/picture-3-5239f80.png
http://img110.xooimage.com/files/f/0/f/picture4-5239f82.png
So I cleaned the way you where generating the position of the PictureBox by using a row principle and increment:
Note:
If you need space at the top to add information start the row count at 1 instead of 0
Note 2:
Here the image dimensions are harcoded but you could use dynamic ones which would be more fluid. I just cleaned the positioning code not the rest.
Replace your function by this one:
Public Shared Sub getPics(website As String, pattern As String)
Dim tempTitles As New List(Of String)()
Dim tempTitles2 As New List(Of String)()
Dim lestitres As New List(Of titlesclass)
Dim webClient As New WebClient()
webClient.Headers.Add("user-agent", "null")
Dim counter As Integer = 0
Dim counter2 As Integer = 0
Dim counter3 As Integer = 0
Dim counter4 As Integer = 1
Dim counter5 As Integer = 0
Dim counter6 As Integer = 0
'If the website happens to go offline, at least your application wont crash.
'Handle default proxy
Dim proxy As IWebProxy = WebRequest.GetSystemWebProxy()
proxy.Credentials = CredentialCache.DefaultCredentials
webClient.Proxy = proxy
Dim content As String = webClient.DownloadString(website)
Dim query = From title In Regex.Matches(content, pattern).Cast(Of Match)
Select New With {Key .Link = String.Concat("http://www.gamestop.com", title.Groups("Data").Value),
Key .Title = title.Groups("Dataa").Value}
Dim titles = tempTitles.Distinct().ToArray() 'remove duplicate titles
Dim titles2 = lestitres.Distinct().ToArray()
lestitres.Clear()
'Count Items
Dim item As Integer = 0
'Count Row
Dim row As Integer = 0
'image: 222*122
For Each letitre In query.Distinct
Dim ImageInBytes() As Byte = webClient.DownloadData(letitre.Link)
Dim ImageStream As New IO.MemoryStream(ImageInBytes)
Dim MyPic As New PictureBox
Dim MyLab As New Label
'x = numéro item fois largeur image
'y = numéro de ligne fois hauteur image
MyPic.Location = New Point(item * 222, row * 122)
MyLab.Location = New Point(item * 222, row * 122)
MyPic.SizeMode = PictureBoxSizeMode.AutoSize
MyLab.Text = letitre.Title
MyPic.Image = New System.Drawing.Bitmap(ImageStream)
Form1.Controls.Add(MyPic)
Form1.Controls.Add(MyLab)
'Bring Labels to front
For Each ctrl As Control In Form1.Controls
'If the control is of type label
If TypeOf ctrl Is Label Then
'Then bring to front
ctrl.BringToFront()
End If
Next
'Increment the item count
item = item + 1
'If item is multiple of 4 or could check 4 then
If item Mod 4 = 0 Then
'Reset counter
item = 0
'Increment Row
row = row + 1
End If
Next
End Sub
Example return:

vb.net string array null reference error

i am creating an array in vb.net:
Dim BoldRows() as String
im adding values to the array here:
Dim detail_table_row as Integer = 1
While reader.read
detail_table_row = detail_table_row + 1
BoldRows(detail_table_row) = detail_table_row
End While
this is inside a loop and detail_table_row is a different number everytime it loops
then outside of my loop i have:
For Each row As Integer In BoldRows
oDoc_detail_table.Range.Rows(row).Range.Font.Bold = True
Next
but i am being told:
Variable 'BoldRows' is used before it has been assigned a value.
Because of
the problem is, i don't know how many elements the array is going to hold
Use List(Of T), From MSDN
Lists are exactly a type of collection which you can use when you don't know a number of items you will put in there.
Then your code will look like
'Integer because you assign Integer value in the List
Dim BoldRows As New List(Of Integer)()
Dim detail_table_row as Integer = 1
While reader.read
detail_table_row = detail_table_row + 1
BoldRows.Add(detail_table_row)
End While
For Each row As Integer In BoldRows
oDoc_detail_table.Range.Rows(row).Range.Font.Bold = True
Next
Arrays are still good in the cases where you know a number of the items.
try this :
Dim detail_table_row as Integer = 0
While reader.read
**ReDim preserve BoldRows(detail_table_row)**
BoldRows(detail_table_row) = detail_table_row
detail_table_row = detail_table_row + 1
End While

How to get each value in an array and show it in a listbox

Hi I am new to VB and I have problems with using array. My code is like that.
This is class FindFactorsObject.vb
Public Sub FindFactors()
count = 0
temp = Convert.ToInt32(Math.Sqrt(_x))
For i As Integer = 1 To temp
If _x Mod i = 0 Then
ReDim array(count)
array(count) = i
count += 1
End If
Next
So I created an array and stored the results. Now I want to display each value in my array in Form.vb and if it is possible can somebody teach me how to make delay for each of the displayed value. Thanks very much
Always declare your variables, if possible to their exact types, you think they will take care of. When you say 'Now I want to display each value in my array in Form.vb' I understood literally: in the Form so, we will print them on your form
Public Sub FindFactors(_x As Integer)
Dim temp As Integer = Convert.ToInt32(Math.Sqrt(_x))
Dim l As New List(Of Integer)
For i As Integer = 1 To temp
If _x Mod i = 0 Then
l.add(i)
End If
Next
Dim pf As New PointF(20, 20)
For Each i As Integer In l
creategraphics.drawstring(i.ToString, New font(font.fontFamily, 24), brushes.cadetblue, pf)
pf = New PointF(pf.X, pf.Y + 30)
Next
End Sub

How can I parse records from a text file to an array?

here is a snippet of the file,
Year 1
mandatory
COM137,Mathematics for Computing,20,2
COM140,Computer Technologies,1-2,20
COM147,Introduction to databases,1-2,20
Year 2
optional
COM606 ..... etc
I want from this an array that reads
COM317,Mathematics for Computing,20,2,M,Year1
COM140,Computer Technologies,1-2,20,M,Year1
this is the layout of each element in the array that i want, but i have no idea how to do it, so the app reads the document see's year 1 stores that in current year then reads mandatory stores that as M in a variable, then i want to add that to an array, then when it sees year 2 it starts again year 2 added to the array element instead.. this is the what i have attempted so far
Dim arrModules As String()
Dim count As Integer = 0
Dim sr As StreamReader = New StreamReader("datasource.txt")
Dim line = sr.ReadLine() ' get each line and store it
Dim currentYear As Integer
Dim moduleStats As String = ""
Dim modArray As String()
While Not sr.EndOfStream
If line.Contains("Year") Then
currentYear = line
ElseIf line.Contains("mandatory") Then
moduleStats = "M"
ElseIf line.Contains("optional") Then
moduleStats = "O"
ElseIf line.Contains("COM") Then
modArray = sr.ReadLine.Split(",")
MsgBox(modArray)
End If
count += 1
sr.ReadLine()
End While
End
// in here is where i am having the problem i don't know how to get all the information i need into one specific array element within an array.. i want to get the year and the module status added to the end of an array element
This being Visual Basic, you could make room for the last two elements this way:
Dim i As Integer = modArray.Length
ReDim Preserve modArray((i - 1) + 2)
modArray(i) = moduleStats
modArray(i + 1) = currentYear.ToString()
Copy the result from Split to a new, larger array and add the additional info.
Dim modArray As String() = {"A", "B", "C"}
Dim finalArray As String() = New String(modArray.Length + 1) {}
Array.Copy(modArray, finalArray, modArray.Length)
finalArray(finalArray.Length - 2) = "M"
finalArray(finalArray.Length - 1) = "Year1"
Or you can simply use
ReDim Preserve modArray(modArray.Length+2)
modArray(modArray.Length - 2) = "M"
modArray(modArray.Length - 1) = "Year1"