Dynamic Labels | VB.Net - vb.net

For every item it finds I want to add a few labels with details like prices and quantity.
I've made something and it only places them once and just rewrites everything. I assume the problem would be because I'm not returning, but if that is the case, I have no clue how to I could do that in this situation. Here's my code
Function addShoppingCartinfo() As System.Windows.Forms.Label
Dim lblQuantityCart As New System.Windows.Forms.Label
Dim lblPriceCart As New System.Windows.Forms.Label
Dim lblProductNameCart As New System.Windows.Forms.Label
Dim lblIndexInCart As New System.Windows.Forms.Label
Dim lblDescriptionCart As New System.Windows.Forms.Label
Dim lblSubtotalPriceInCart As New System.Windows.Forms.Label
Dim lblTotalPriceInCart As New System.Windows.Forms.Label
Dim var_Y As Integer = 47
Dim var_YTotal As Integer = 104
Dim var_YDescription As Integer = 72
For Each ItemInCart In list_Cart
For Each id In arr_ID
If id = ItemInCart Then
var_AmountInCart += 1
var_Y += var_AmountInCart
var_YTotal += var_AmountInCart
var_YDescription += var_AmountInCart
var_QuantityIndex = list_Cart.IndexOf(ItemInCart)
var_WinkelWagenIndex = Array.IndexOf(arr_ID, id)
var_SubTotalPrice = arr_Prices(var_WinkelWagenIndex) * list_Quantity(var_QuantityIndex)
list_Prices.Add(var_SubTotalPrice)
WinkelWagen.Controls.Add(lblQuantityCart)
WinkelWagen.Controls.Add(lblPriceCart)
WinkelWagen.Controls.Add(lblProductNameCart)
WinkelWagen.Controls.Add(lblIndexInCart)
WinkelWagen.Controls.Add(lblDescriptionCart)
WinkelWagen.Controls.Add(lblSubtotalPriceInCart)
WinkelWagen.Controls.Add(lblTotalPriceInCart)
For Each price In list_Prices
var_TotalPrice += price
Next
lblQuantityCart.Text = list_Quantity(var_QuantityIndex)
lblQuantityCart.Location = New Point(539, var_Y)
lblIndexInCart.Text = var_AmountInCart
lblIndexInCart.Location = New Point(494, var_Y)
lblIndexInCart.Visible = False
lblPriceCart.Text = "SRD " & arr_Prices(var_WinkelWagenIndex)
lblPriceCart.Location = New Point(494, var_Y)
lblDescriptionCart.Text = arr_Names(var_WinkelWagenIndex)
lblDescriptionCart.Location = New Point(240, var_Y)
lblSubtotalPriceInCart.Text = "SRD" & var_SubTotalPrice
lblSubtotalPriceInCart.Location = New Point(640, var_Y)
lblProductNameCart.Text = arr_Names(var_WinkelWagenIndex)
lblProductNameCart.Location = New Point(113, var_Y)
End If
Next
Next
lblTotalPriceInCart.Text = "SRD" & var_TotalPrice
lblTotalPriceInCart.Location = New Point(640, var_YTotal * var_AmountInCart)
Debug.WriteLine("this has " & var_AmountInCart & " Quantity")
End Function
When I've got 2 items it does this. (Image)

Related

Speed up my function - Dynamic button creation vb.net

I have a function that creates button dynamically based on a database table, there are about 250 records inside. Everything is working properly but I'd like to make it faster but I don't know how.
Maybe it's due to the language I don't know.
Actually, on my development machine, it takes about 56 seconds to load. I'm not an experienced developper so maybe I'm missing something.
The problem is that on the client machine, that has only 4Go of RAM, the loading time is much bigger, 2.5 to 3.5 minutes.
Thans you for your help.
This is my code :
Public Sub LoadProducts()
Me.ProgressBar1.Value = 0
Me.ProgressBar1.Visible = True
Dim oSim As New SimFonction
Dim str As String = "SELECT * FROM produits ORDER BY ref;"
Dim oCmd As New MySqlCommand(str, oSim.ConnectDb)
Dim oData As New DataSet
Dim oAdapt As New MySqlDataAdapter With {
.SelectCommand = oCmd
}
oAdapt.Fill(oData)
oSim.conn.Close()
recCount = oData.Tables(0).Rows.Count
Dim btn(recCount) As Button
Dim x, y, j As Integer
oAdapt = Nothing
oCmd = Nothing
str = Nothing
Dim ref As String
x = 0
y = 0
Dim valeurIncr As Integer = 100 / recCount
valeurBar = 0
i = 0
For i = 0 To oData.Tables(0).Rows.Count - 1
If Me.ProgressBar1.Value >= 90 Then
Me.ProgressBar1.Value = 0
End If
If j = 5 Then
y += 90
j = 0
x = 0
End If
x += 90
btn(i) = New Button With {
.Parent = productPanel,
.Location = New Point(x, y),
.Height = 90,
.Width = 90,
.Font = New Font("Microsoft Sans Serif", 14, FontStyle.Bold),
.ForeColor = Color.Orange,
.UseVisualStyleBackColor = True,
.TextAlign = ContentAlignment.BottomCenter
}
ref = oData.Tables(0).Rows(i).Item("ref").ToString
If IsDBNull(oData.Tables(0).Rows(i).Item("photo")) Then
btn(i).Text = oData.Tables(0).Rows(i).Item("ref").ToString
btn(i).Tag = oData.Tables(0).Rows(i).Item("ref").ToString
btn(i).Name = "bt" & ref
Else
Dim photoP As New IO.MemoryStream(CType(oData.Tables(0).Rows(i).Item("photo"), Byte()))
btn(i).BackgroundImage = Image.FromStream(photoP)
btn(i).BackgroundImageLayout = ImageLayout.Stretch
btn(i).Tag = oData.Tables(0).Rows(i).Item("ref").ToString
btn(i).Text = oData.Tables(0).Rows(i).Item("ref").ToString
btn(i).Name = "bt" & ref
photoP = Nothing
End If
If oSim.CheckProduiEnStock(ref) = False Then
btn(i).Enabled = False
End If
AddHandler btn(i).Click, AddressOf ButtonClicked
j += 1
Me.ProgressBar1.Value += 1
btn(i) = Nothing
Next
Me.ProgressBar1.Visible = False
End Sub
You may use the following command:
At the beginning: Me.SuspendLayout() ,and
at the end: Me.ResumeLayout()

VB Net What is the fastest way to generate object created programmatically

I have create an application that need to generate about 100 to 1000 object programmatically. This object will be generated with the same amount in the database. In order to accomplish objective above, of course i need to call the data from database, then i looping through each data to generate each object. But it takes such a very long time before it done. I hoping that you have an alternative way beside how i do this.
Below is my code to call the data from database
Dim tbls As New DataTable
Using cons As New SqlConnection(stringconnection)
Dim sqls = "select * from tbsectiondetail where IDSection = '" & txtIDSection.Text &
"' AND KodeLocation like '%" & txtCari.Text &
"%' AND Status like '%" & cbStatus.Text &
"%' ORDER BY Status DESC"
Dim adps As New SqlDataAdapter(sqls, cons)
adps.Fill(tbls)
adps.Dispose()
cons.Dispose()
End Using
If i just generate the data only, its just take only 1 to 2 second. So i don't think there is problem about how i call the data from database
And below is how i generate the object through looping the data
Dim resultsx As DataRow() = tbls.Select("")
If resultsx.Count > 0 Then
For iX = 0 To resultsx.Count - 1
'CREATE A VARIABLE
Dim IDSectionDetail = resultsx(iX)("IDSectionDetail").ToString
Dim NamaLocation = resultsx(iX)("NamaLocation").ToString
Dim SectionKode = resultsx(iX)("KodeLocation").ToString
Dim StatusSection = resultsx(iX)("Status").ToString
Dim StatusSectionAt = resultsx(iX)("StatusAt").ToString
Dim StatusC1 = resultsx(iX)("StatusC1").ToString
Dim StatusC2 = resultsx(iX)("StatusC2").ToString
'GENERATE A PANEL
Dim pnlContainer As New Panel
pnlContainer.Size = New Size(290, 200)
Tablex.Controls.Add(pnlContainer, curColumn, rowNo)
pnlContainer.Dock = DockStyle.Fill
Dim pnlHeader As New Panel
pnlContainer.Controls.Add(pnlHeader)
pnlHeader.Dock = DockStyle.Top
pnlHeader.Size = New Size(pnlContainer.Width, 35)
If StatusSection = "Open" Then
pnlHeader.BackColor = Color.DarkSlateGray
Else
pnlHeader.BackColor = Color.FromArgb(185, 58, 50)
End If
pnlContainer.Controls.SetChildIndex(pnlHeader, 2)
'GENERATE LABEL HEADER
Dim lblHeader As New Label
lblHeader.Text = NamaLocation & " - " & SectionKode
pnlHeader.Controls.Add(lblHeader)
lblHeader.Font = New Font("Century Gothic", 9, FontStyle.Bold Or FontStyle.Italic)
lblHeader.ForeColor = Color.White
lblHeader.Location = New Point(8, 7)
lblHeader.AutoSize = True
'GENERATE LABEL STATUS
Dim lblStatus As New Label
lblStatus.Text = "Status : " & StatusSection
pnlHeader.Controls.Add(lblStatus)
lblStatus.Font = New Font("Century Gothic", 8, FontStyle.Bold Or FontStyle.Italic)
lblStatus.ForeColor = Color.White
lblStatus.TextAlign = ContentAlignment.MiddleRight
lblStatus.Height = pnlHeader.Height
lblStatus.Dock = DockStyle.Right
lblStatus.AutoSize = True
'GENERATE PANEL FOOTER
Dim pnlFooter As New Panel
pnlContainer.Controls.Add(pnlFooter)
pnlFooter.Dock = DockStyle.Fill
pnlFooter.Size = New Size(pnlFooter.Width, 35)
pnlFooter.BackColor = Color.White
pnlContainer.Controls.SetChildIndex(pnlFooter, 0)
'GENERATE BUTTON DETAIL
Dim btnDetail As New Button
pnlFooter.Controls.Add(btnDetail)
btnDetail.Name = "btn" & SectionKode
btnDetail.FlatStyle = FlatStyle.Flat
btnDetail.FlatAppearance.BorderColor = Color.FromArgb(46, 74, 98)
btnDetail.FlatAppearance.BorderSize = 1
btnDetail.FlatAppearance.MouseDownBackColor = Color.Gold
btnDetail.FlatAppearance.MouseOverBackColor = Color.Gold
btnDetail.BackColor = Color.DarkSlateGray
btnDetail.Text = "Detail"
btnDetail.Image = My.Resources.search2_icon
btnDetail.Font = New Font("Century Gothic", 8, FontStyle.Bold)
btnDetail.TextImageRelation = TextImageRelation.TextBeforeImage
btnDetail.Location = New Point(181, 84)
btnDetail.Anchor = AnchorStyles.Right And AnchorStyles.Top
btnDetail.Size = New Size(75, 28)
btnDetail.ForeColor = Color.White
AddHandler btnDetail.Click, Sub() DetailSection(IDSectionDetail, SectionKode)
curColumn += 1
If curColumn >= 5 Then
curColumn = 0
RowCount += 1
Tablex.RowCount = RowCount
rowNo += 1
End If
Next
End If
pnlFill.Controls.Add(Tablex)
Actually there is still more object to generate through that looping. But from my analysis, the looping already take such a long time already just from code above.
The result of the generated object
I just wonder if there is another and faster alternative to generate such object. Or do i need to give up to design and just make it simple black and white ?

Highlight a row in Datagridview based on textbox value

Good Evening.
I have a program in VB.Net that refreshes datagridview after you edit some data my problem here is im populating over 1000 records.
Let say Im editing row 999 and after i click update the data will refresh causing the datagridview to return at the top (The blue highlighter)
My goal here is how can I maintain it to its current position after update?
My solution here is highlight the data where Textbox1 = value
Is this possible like this?
'SAMPLE CODE
Datagridview1.Column(0).value.BlueHighLighter = Textbox1.text
Pls see my code on how i refresh DGV
Dim con11 As MySqlConnection = New MySqlConnection("server=192.168.2.87;userid=root;password=admin1950;database=inventory")
Dim sql1 As MySqlCommand = New MySqlCommand("select PONo,ItemCode,Description,QtyPack,PackUoM,QtyStan,StanUoM,UnitPrice,Total,Remarks,ExpiryDate from Receiving where RINo = '" & Add_Receiving_Items.TextBox1.Text & "';", con1)
Dim ds1 As DataSet = New DataSet
Dim adapter1 As MySqlDataAdapter = New MySqlDataAdapter
con1.Open()
adapter1.SelectCommand = sql1
adapter1.Fill(ds1, "MyTable")
Add_Receiving_Items.DataGridView1.DataSource = ds1.Tables(0)
con1.close()
With Add_Receiving_Items.DataGridView1()
.RowHeadersVisible = False
.Columns(0).HeaderCell.Value = "PO No"
.Columns(1).HeaderCell.Value = "Item Code"
.Columns(2).HeaderCell.Value = "Description"
.Columns(3).HeaderCell.Value = "Quantity/Pack"
.Columns(4).HeaderCell.Value = "Packaging UoM"
.Columns(5).HeaderCell.Value = "Quantity/Pc"
.Columns(6).HeaderCell.Value = "Standard UoM"
.Columns(7).HeaderCell.Value = "Unit Price"
.Columns(8).HeaderCell.Value = "Total"
.Columns(9).HeaderCell.Value = "Remarks"
.Columns(10).HeaderCell.Value = "Expiry Date"
End With
Add_Receiving_Items.DataGridView1.Columns.Item(0).Width = 80
Add_Receiving_Items.DataGridView1.Columns.Item(1).Width = 80
Add_Receiving_Items.DataGridView1.Columns.Item(2).Width = 120
Add_Receiving_Items.DataGridView1.Columns.Item(3).Width = 86
Add_Receiving_Items.DataGridView1.Columns.Item(4).Width = 68
Add_Receiving_Items.DataGridView1.Columns.Item(5).Width = 75
Add_Receiving_Items.DataGridView1.Columns.Item(6).Width = 68
Add_Receiving_Items.DataGridView1.Columns.Item(7).Width = 70
Add_Receiving_Items.DataGridView1.Columns.Item(8).Width = 80
Add_Receiving_Items.DataGridView1.Columns.Item(9).Width = 105
Add_Receiving_Items.DataGridView1.Columns.Item(10).Width = 63
Add_Receiving_Items.DataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter
Add_Receiving_Items.DataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter
With Add_Receiving_Items.DataGridView1
.RowsDefaultCellStyle.BackColor = Color.WhiteSmoke
.AlternatingRowsDefaultCellStyle.BackColor = Color.Lavender
End With
TYSM for future help
Use DataGridView.CurrentRow property. But please be aware that CurrentRow is ReadOnly, you must use CurrentCell
Before refreshing your data store Dim oldIndex = DataGridView.CurrentRow.Index and after the refresh set DataGridView.CurrentCell = DataGridView.Rows(oldIndex).Cells(0)
EDIT:
How to test the Code
Create a form with a Button1 and a DataGridView1 with two columns and paste the following code:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For i = 1 To 5
DataGridView1.Rows.Add("foo" & i, "bar" & i)
Next
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim currentIndex = DataGridView1.CurrentRow.Index
currentIndex += 1
If currentIndex >= DataGridView1.Rows.Count Then currentIndex = 0
DataGridView1.CurrentCell = DataGridView1.Rows(currentIndex).Cells(0)
End Sub
End Class
EDIT:
Dim oldIndex = DataGridView.CurrentRow.Index
'Put your code here on how you refresh your data
DataGridView.CurrentCell = DataGridView.Rows(oldIndex).Cells(0)

DataGridView ScrollBar bug

When I get data for the DataGridView, my form freezes until the While loop completes, but then my scrollbar worked fine. I tried calling Application.DoEvents(); but that didn't work either.
If I get the data in a thread, then my form does not freeze, but the scrollbar disables and does not work after the While completes. I tried a BackgroundWorker but the scrollbar has a problem when using that too.
Private Sub dg()
myth = New Threading.Thread(AddressOf dgd)
myth.IsBackground = True
myth.Start()
End Sub
Private Sub dgd()
Dim x As Integer
If DataGridView1.Rows.Count = 0 Then x = 0 Else x = DataGridView1.Rows.Count
Try
Dim conn35a As New OleDbConnection("connstring")
Dim cmd35a As New OleDbCommand
cmd35a.CommandText = "Select count(*) from asd where downur Is Null"
cmd35a.CommandType = CommandType.Text
cmd35a.Connection = conn35a
conn35a.Open()
Dim returnValueaa As Integer = cmd35a.ExecuteScalar()
conn35a.Close()
Dim komut As String = "Select * from asd where downur Is Null"
Dim conn2 As New OleDbConnection("connstring")
conn2.Open()
Dim cmd2 As New OleDbCommand(komut, conn2)
Dim dr2 As OleDbDataReader = cmd2.ExecuteReader
If dr2.HasRows Then
While dr2.Read
Dim conn35 As New OleDbConnection("connstring")
Dim cmd35 As New OleDbCommand
cmd35.CommandText = "select count(*) from grid where ur = '" + dr2.Item("ur").ToString + "'"
cmd35.CommandType = CommandType.Text
cmd35.Connection = conn35
conn35.Open()
Dim returnValuea = cmd35.ExecuteScalar()
conn35.Close()
If returnValuea = 0 Then
DataGridView1.Rows.Add()
DataGridView1.Rows.Item(x).Cells(0).Value = x + 1
DataGridView1.Rows.Item(x).Cells(4).Value = "ID"
DataGridView1.Rows.Item(x).Cells(5).Value = dr2.Item("ur").ToString
DataGridView1.Rows.Item(x).Cells(6).Value = dr2.Item("ch").ToString
DataGridView1.Rows.Item(x).Cells(7).Value = dr2.Item("ti").ToString
DataGridView1.Rows.Item(x).Cells(8).Value = ".."
Dim client2 As New WebClient
Dim url As String = dr2.Item("pic").ToString
DataGridView1.Rows.Item(x).Cells(12).Value = New Bitmap(New MemoryStream(client2.DownloadData(url)))
DataGridView1.Rows.Item(x).Cells(13).Value = dr2.Item("vi")
DataGridView1.Rows.Item(x).Cells(14).Value = dr2.Item("su").ToString()
Dim con4 As New OleDbConnection("connstring")
con4.Open()
Dim cmd5 = New OleDbCommand("INSERT INTO grid (ur) VALUES (#ur)", con4)
cmd5.CommandType = CommandType.Text
cmd5.Parameters.Add("#ur", OleDbType.VarChar, 500).Value = dr2.Item("ur").ToString
cmd5.ExecuteNonQuery()
con4.Close()
x += 1
End If
End While
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I had the same problem.
I solved this by removing the Thread and calling the method directly

Dynamically add checkboxes to groupbox

i am trying to dynamically add checkboxes to a groupd box based on the amount of rows in a datatable. when looping through i get my first result but i am not able to get the next results to show...here is my code
Dim q As String
Dim qt As DataTable
Dim gbHeight As Integer = 40
Dim checkHG As Integer = 5
Dim checkHN As Integer = 5
q = "Select * from loads where filenumber = " & Shipments2.txtFileNumber.Text
qt = GetSQL(q)
For i = 0 To qt.Rows.Count - 1
Dim items As New List(Of LoadDetails)
Dim ld As New LoadDetails
items = ld.GetListBySQL("select * from loadDetails where LoadNumber = " & qt.Rows(i).Item("id"))
For Each item As LoadDetails In items
Dim checkgross = New CheckBox
Dim checknet = New CheckBox
gbHeight += 20
'add checkbox control to form
checkgross.Location = New Point(40, checkHG + 20)
checkgross.Text = item.Description & " (Gross)"
checkgross.Size = New Size(250, 20)
checkgross.Name = item.ProductCode.ToString & "-gross"
gbGross.Size = New Size(329, gbHeight)
gbGross.Controls.Add(checkgross)
rbPrintingNet.Location = New Point(rbPrintingNet.Location.X, rbPrintingNet.Location.Y + 40)
checknet.Location = New Point(40, checkHN + 20)
checknet.Text = item.Description & " (Net)"
checknet.Size = New Size(250, 20)
checknet.Name = item.ProductCode.ToString & "-net"
gbNet.Location = New Point(44, rbPrintingNet.Location.Y + 25)
gbNet.Size = New Size(329, gbHeight)
gbNet.Controls.Add(checknet)
Me.Size = New Size(Me.Size.Width, Me.Size.Height + 50)
Next
Next
All your controls are on directly top of each other:
checkgross.Location = New Point(40, checkHG + 20)
Since checkHG never changes. Change the Location() for each dynamic control...