Trying to create text boxes dynammically and remove them - vb.net

I am using VB.NET vb 2008 . I am trying to create text boxes dynammically and remove them here is the code i have written so far
Private Sub setTextBox()
Dim num As Integer
Dim pos As Integer
num = Len(word)
temp = String.Copy(word)
Dim intcount As Integer
remove()
GuessBox.Visible = True
letters.Visible = True
pos = 0
'To create the dynamic text box and add the controls
For intcount = 0 To num - 1
Txtdynamic = New TextBox
Txtdynamic.Width = 20
Txtdynamic.Visible = True
Txtdynamic.MaxLength = 1
Txtdynamic.Location = New Point(pos + 5, 0)
pos = pos + 30
'set the font size
Txtdynamic.Font = New System.Drawing.Font("Verdana", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Txtdynamic.Name = "txtdynamic_" & intcount & "_mycntrl"
Txtdynamic.Enabled = False
Txtdynamic.Text = ""
Panel1.Controls.Add(Txtdynamic)
Next
Panel1.Visible = True
Controls.Add(Panel1)
Controls.Add(GuessBox)
Controls.Add(letters)
letter = ""
letters.Text = ""
hang_lable.Text = ""
tries = 0
End Sub`enter code here`
Function remove()
For Each ctrl In Panel1.Controls
Panel1.Controls.Remove(ctrl)
Next
End Function
I am able to create the textboxes but only a few of them are removed. by using For Each ctrl In Panel1.Controls it doesn't retrieve all the controls and some ae duplicated as well.

Change your remove to
Sub remove()
For i As Integer = Panel1.Controls.Count - 1 To 0 Step -1
Panel1.Controls.Remove(Panel1.Controls(i))
Next i
End Sub
If I am not mistaken you should not change a collection in a loop that you are currently looping, using a for each. The safest ways would be to use the index, in reverse, so that the position is not affected.

Related

How to dynamicallty create multiple controls at runtime

I am trying to add multiple labels to a userform at runtime
It's for the player names of a board game; and until the game starts the number of players are not known. I have managed to figure out for myself how to use the dynamic array function to create the list of players. I used a For.....Next loop to add the player names. I thought I could do that to add the labels to the form, but it only adds one. Depending on where the new control type is declared, it either adds the first player only, or the last player
This code produces one label only within the groupbox, the last player
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Players_Num As Integer = InputBox("Enter the number of players")
Dim Players(Players_Num) As String
Dim newText As New Label
For i = 0 To Players_Num - 1
Players(i) = InputBox("Enter player name")
Next
'This piece of code was jsut for me to test that I was successfully using a For...Loop
'to add the players names, and will be deleted later on
For x = 0 To Players_Num - 1
MessageBox.Show(Players(x))
Next
For z = 0 To Players_Num - 1
newText.Name = "txt" & Players(z)
newText.Text = Players(z)
newText.Size = New Size(170, 20)
newText.Location = New Point(12 + 5, 12 + 5)
GroupBox1.Controls.Add(newText)
Next
End Sub
End Class
This one places only the first player
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Players_Num As Integer = InputBox("Enter the number of players")
Dim Players(Players_Num) As String
For i = 0 To Players_Num - 1
Players(i) = InputBox("Enter player name")
Next
'This piece of code was jsut for me to test that I was successfully using a For...Loop
'to add the players names, and will be deleted later on
For x = 0 To Players_Num - 1
MessageBox.Show(Players(x))
Next
For z = 0 To Players_Num - 1
Dim newText As New Label
newText.Name = "txt" & Players(z)
newText.Text = Players(z)
newText.Size = New Size(170, 20)
newText.Location = New Point(12 + 5, 12 + 5)
GroupBox1.Controls.Add(newText)
Next
End Sub
End Class
I've tried this in vs 2015 and 2019 Community
Where is it going wrong?
From the looks of the code, you are correctly creating the controls but their location is the same for all of them, essentially, they are being place one of top of the other, the first is hidden with the second, which is hidden with the third.
The line
newText.Location = New Point(12 + 5, 12 + 5)
needs to be modified to place the labels at different locations.
Perhaps, something like:
newText.Location = New Point(12 + 5, 12 + (z * 25))
This will vertically align the labels with a gap of 25 between them
You are placing them all in the same location
newText.Location = New Point(12 + 5, 12 + 5)
Use your 'z' index to place them at different locations in order to be able to see them
For me it is easier to contain controls in a TableLayoutPanel then add the TLP to what ever control collection, such as a GroupBox This way you can couple a Label with TextBox, for example. Here's an example how you can create controls from a DataTable. In your case you would only need 1 ColumnStyle for labels, I just thought I would show you a good practice for future shortcuts. (I rarely use the designer to place controls)
'Start test data
Dim DtTable As New DataTable
With DtTable
Dim NewDtRow As DataRow = .NewRow
For i As Integer = 0 To 25
Dim DtCol As New DataColumn With {.ColumnName = "Col" & i, .DataType = GetType(String)}
.Columns.Add(DtCol)
NewDtRow(DtCol.ColumnName) = "Test" & i
Next
.Rows.Add(NewDtRow)
End With
'End test data
Dim TLP1 As New TableLayoutPanel With {.Name = "TlpFields"}
With TLP1
.BorderStyle = BorderStyle.Fixed3D
.CellBorderStyle = TableLayoutPanelCellBorderStyle.Inset
.AutoScroll = True
.AutoSize = True
.RowStyles.Clear()
.ColumnStyles.Clear()
.Dock = DockStyle.Fill
.ColumnCount = 2
.ColumnStyles.Add(New ColumnStyle With {.SizeType = SizeType.AutoSize})
End With
For Each DtCol As DataColumn In DtTable.Columns
With TLP1
.RowCount += 1
.RowStyles.Add(New RowStyle With {.SizeType = SizeType.AutoSize})
'create labels
.Controls.Add(New Label With {
.Text = DtCol.ColumnName,
.Anchor = AnchorStyles.Right}, 0, .RowCount)
'create textboxs
Dim TxtBox As New TextBox With {
.Name = "TextBox" & DtCol.ColumnName,
.Size = New Size(170, 20),
.Anchor = AnchorStyles.Left}
'add binding
TxtBox.DataBindings.Add("Text", DtTable, DtCol.ColumnName)
.Controls.Add(TxtBox, 1, .RowCount)
End With
Next
Controls.Add(TLP1)

Basic Name Sorting Program using VB.net

My teacher has instructed our class to create a basic word sorting program the 'old fashioned way' in visual basic. So comparing two array values, a and b, then if one is considered higher in the order than the other, swap them if not do nothing, continue until there are no more swaps. Here is the code I have so far:
Imports System.IO
Imports System
Public Class Form1
Public arrText As New ArrayList()
Private Sub btnImprt_Click(sender As Object, e As EventArgs) Handles btnImprt.Click
'Dim OpenAnswerFile As New OpenFileDialog
Dim objReader As New StreamReader("c:\Users\Adam\Desktop\unSortList.txt")
Dim sLine As String = ""
Dim arrText As New ArrayList()
Do
sLine = objReader.ReadLine()
If Not sLine Is Nothing Then
arrText.Add(sLine)
End If
Loop Until sLine Is Nothing
objReader.Close()
Dim i As Integer = 0
txtImport.Text = arrText(i)
End Sub
Private Sub btnSort_Click(sender As Object, e As EventArgs) Handles btnSort.Click
Dim i As Integer = 0
Dim a As Integer = i + 1
txtImport.Text = i
txtImport.Text = a
Dim Temp As String
Dim Change As Boolean = True
While Change = True
Change = False
For Each i In arrText(i) - 1
If String.Compare(arrText(i), arrText(i + 1)) = 1 Then
Change = True
Temp = arrText(i)
arrText(i) = arrText(i + 1)
arrText(i + 1) = Temp
End If
Next
i = 0
End While
txtSort.Text = arrText(39)
End Sub
My problem is that I am getting an Index error and I'm not sure where the error is located as the logic seems fine.
And yes I am aware of the sorting function built into Visual Basic. but as the teacher said. No cheating.
Your code has several flaws, which I'm ignoring and just concentrating on the sorting part, as your query is related to that. Replace your sort loop with the following and check again. The basic problem was that your loop should only iterate up to List.Count - 2 and not List.Count - 1 because you're comparing List(i) and List(i + 1) inside the loop:
Dim Temp As String
Dim Change As Boolean = True
While Change
Change = False
For i = 0 To arrText.Count() - 2
If String.Compare(arrText(i), arrText(i + 1)) = 1 Then
Change = True
Temp = arrText(i)
arrText(i) = arrText(i + 1)
arrText(i + 1) = Temp
End If
Next
End While

Print multiple images in vb.net

In VB.NET, I need to print multiple Images of bar codes by arranging them in tabular format. For now what I am doing is, Creating the bar codes and adding them in new picture box. These Picture boxes are added on a panel which I am creating on form at run time and print that panel (with picture boxes in 4x9 table).
But, when I need to print more that 36 bar codes, this idea doesn't work.
So, Please suggest me some improvements in my code or any other way to do this job.
I am sorry, here is the code for generating images and adding them to the panel..
''' Method for create bar code images with a loop and adding them to the panel by picture box...
Private Function GetBarcodeText(RowId As Guid)
Dim BarcodeValue As StringBuilder = New StringBuilder(96)
Dim temp As New StringBuilder
Dim data As String
Dim param = New SqlParameter()
Dim imageNo As Integer = 0
Dim colorValue As String = ""
Dim scaleValue As String = ""
'' Adding the panel on the form which is dynamically created
Me.Controls.Add(outputPanel)
'' Setting the Initial size for the panel
outputPanel.Size = New Point(794, 112)
outputPanel.Name = "outputPanel"
outputPanel.BackColor = Drawing.Color.White
param.ParameterName = "#RowId"
param.Value = RowId
param.SqlDbType = SqlDbType.UniqueIdentifier
' Get the particular row of data from database
dt = objStockProvider.GetBarcodeDetails(param)
' GET colour code
Dim color As String = dt.Rows(0)("COLOUR").ToString()
Dim countColors As Integer = 0
' Get the color code numbers
param.ParameterName = "#Dscale"
param.Value = dgvViewTickets.CurrentRow.Cells("SCALE").Value.ToString()
countColors = objStockProvider.CountColorCodes(param)
For i = 1 To countColors
For j As Integer = 1 + ((12 / countColors) * (i - 1)) To (12 / countColors) * i
If dt.Rows(0)("S" + j.ToString()) <> 0 Then
Dim totalTicketsForASize As Integer
totalTicketsForASize = dt.Rows(0)("S" + j.ToString())
For k As Integer = 1 To totalTicketsForASize
' Set Bar code value which has to create
BarcodeValue = "123456789012"
' Create Barcode Image for given value
Dim image = GetBarcodeImage(BarcodeValue, colorValue, scaleValue)
If image IsNot Nothing Then
'' Create picture box to contain generated Image.
Dim pcbImage As New PictureBox
pcbImage.Width = W
pcbImage.Height = H
pcbImage.Image = image
pcbImage.Location = New Point(X, Y)
imageNo += 1
If imageNo Mod 4 = 0 Then
X = 15
Y += H
outputPanel.Height += H
Else
X += W
Y = Y
End If
pcbImage.Visible = True
'' Adding picture box to panel
outputPanel.Controls.Add(pcbImage)
End If
Next
End If
Next
color = color.Substring(color.IndexOf(",") + 1, color.Length - color.IndexOf(",") - 1)
Next
PrintGeneratedTickets()
End Function
Now, I am printing the panel by following method:
Private Sub PrintGeneratedTickets()
bmp = New Bitmap(outputPanel.DisplayRectangle.Width, outputPanel.DisplayRectangle.Height)
Dim G As Graphics = Graphics.FromImage(bmp)
G.DrawRectangle(Pens.White, New Rectangle(0, 0, Me.outputPanel.DisplayRectangle.Width, Me.outputPanel.DisplayRectangle.Height))
Dim Hdc As IntPtr = G.GetHdc()
SendMessage(outputPanel.Handle, WM_PRINT, Hdc, DrawingOptions.PRF_OWNED Or DrawingOptions.PRF_CHILDREN Or DrawingOptions.PRF_CLIENT Or DrawingOptions.PRF_NONCLIENT)
G.ReleaseHdc(Hdc)
pndocument.DocumentName = bmp.ToString()
Dim previewmode As New PrintPreviewDialog
previewmode.Document = pndocument
previewmode.WindowState = FormWindowState.Maximized
previewmode.PrintPreviewControl.Zoom = 1
pndocument.DefaultPageSettings.Margins.Top = 10
pndocument.DefaultPageSettings.Margins.Bottom = 30
pndocument.DefaultPageSettings.Margins.Left = 16
pndocument.DefaultPageSettings.Margins.Right = 16
pndocument.DefaultPageSettings.Landscape = False
' Set other properties.
previewmode.PrintPreviewControl.Columns = 4
previewmode.PrintPreviewControl.Rows = 9
previewmode.ShowDialog()
Dim file As String = DateTime.Now.ToString()
file = Path.GetFullPath("D:\Bar Codes\" + file.Replace("/", "-").Replace(":", ".") + ".bmp")
bmp.Save(file)
G.Dispose()
outputPanel.Controls.Clear()
End Sub
This code is working fine but what I need to do, is to fix the number of images (4x9) per page. But when I am trying to create more than it, that all are printing on a single page with compressed size.
Also when trying to re-run the code, It shows nothing in preview..
Some body please suggest the correction in code so that I can reprint the tickets and use paging for more than 36 images.
Well, Printing the Images on a panel was not a good idea.. I replaced the panel and created an array of images and used the print document directly and print after arranging images on it.
Thanks.

multiple DatagridView Rendering Vb.net

I'm able to add multiple datagridview 1 after another on panel.
by adding code of SysDragon from the same forum
Dim AllDataGrids As List(Of My_custom_DGV)
Dim lastCtrl As Control
AllDataGrids = New List(Of My_custom_DGV)
For j As Int32 = 0 To 3
Dim aDataGridView As New My_custom_DGV()
aDataGridView.for_date = ""
aDataGridView._count = week_count
aDataGridView.Dock = DockStyle.Top
aDataGridView.Dock = DockStyle.Right
aDataGridView.Dock = DockStyle.Left
aDataGridView.Dock = DockStyle.Bottom
AllDataGrids.Add(aDataGridView)
Next j
For i As Integer = 1 To 3
Dim dgv As My_custom_DGV = AllDataGrids(i)
' Dim dgv As DataGridView = AllDataGrids(i)
If dataGrid_Panel.Controls.Count.Equals(0) Then
dgv.Top = DataGridView1.Height + 20
Else
lastCtrl = dataGrid_Panel.Controls(dataGrid_Panel.Controls.Count - 1)
dgv.Top = lastCtrl.Top + lastCtrl.Height + 5
End If
dataGrid_Panel.Controls.Add(dgv)
Next
the problem is that when i scroll in between them then it is looking very bad(i.e. as i scroll,it is repeating the the image on panel again and again). does it render the view again when i Scroll,and may be calling the paint method of datagridview repeatedly. if yes then what is the solution?
Thanks.

Error on inserting new line on gridview

I am trying to add a new row into a gridview but for some reason i'm having a problem in the for loop.
Directly goes to dtCurrentTable.Rows.Add(drCurrentRow) and of course, have an error "'row' argument cannot be null.Parameter name: row", because the dtcurrentTable.NewRow was not executed.
Why is this happening?
Private Sub AddNewRowToGrid()
Dim rowIndex As Integer = 0
If Not IsNothing(ViewState("CurrentTable")) Then
Dim dtCurrentTable As DataTable = CType(ViewState("CurrentTable"), DataTable)
Dim drCurrentRow As DataRow = Nothing
If dtCurrentTable.Rows.Count > 0 Then
For i as Integer = 1 To i <= dtCurrentTable.Rows.Count
' Extraem-se os valores das Textbox
Dim box1 As TextBox = Dados.Rows(rowIndex).Cells(0).FindControl("Artigo")
Dim box2 As TextBox = Dados.Rows(rowIndex).Cells(1).FindControl("Descricao")
Dim box3 As TextBox = Dados.Rows(rowIndex).Cells(2).FindControl("IVA")
Dim box4 As TextBox = Dados.Rows(rowIndex).Cells(3).FindControl("PU")
Dim box5 As TextBox = Dados.Rows(rowIndex).Cells(4).FindControl("Desconto")
Dim box6 As TextBox = Dados.Rows(rowIndex).Cells(5).FindControl("UN")
Dim box7 As TextBox = Dados.Rows(rowIndex).Cells(6).FindControl("Quantidade")
Dim box8 As TextBox = Dados.Rows(rowIndex).Cells(7).FindControl("TotalLiquido")
drCurrentRow = dtCurrentTable.NewRow
dtCurrentTable.Rows(i - 1)("Artigo") = box1.Text
dtCurrentTable.Rows(i - 1)("Descricao") = box2.Text
dtCurrentTable.Rows(i - 1)("IVA") = box3.Text
dtCurrentTable.Rows(i - 1)("PU") = box4.Text
dtCurrentTable.Rows(i - 1)("Desconto") = box5.Text
dtCurrentTable.Rows(i - 1)("UN") = box6.Text
dtCurrentTable.Rows(i - 1)("Quantidade") = box7.Text
dtCurrentTable.Rows(i - 1)("TotalLiquido") = box8.Text
rowIndex += 1
Next i
dtCurrentTable.Rows.Add(drCurrentRow)
ViewState("CurrentTable") = dtCurrentTable
Dados.DataSource = dtCurrentTable
Dados.DataBind()
End If
Else
Response.Write("ViewState null")
End If
SetPreviousData()
End Sub
Your For loop is defined wrong, thats why you're getting an error:
For i as Integer = 1 To i <= dtCurrentTable.Rows.Count
evaluates to
For i as Integer = 1 To True
(because i is always <= Rows.Count)
which VB translates as
For i as Integer = 1 To -1
which means your loop never runs.
It
should be
For i as Integer = 1 To dtCurrentTable.Rows.Count
Also, there's something odd about the way you use drCurrentRow = dtCurrentTable.NewRow. Why is that inside the loop when you don't do anything with it in the loop? It gets executed multiple times and then dtCurrentTable.Rows.Add(drCurrentRow) only gets called once.
Its hard for me to correct because I can't figure out what you're trying to do, but that bit looks dodgy to me.