Size of labels in a TableLayoutPanel - vb.net

I've been stuck in this for two hours now. I googled for the answer a lot, and still can't figure out what's wrong with my program.
I have a TableLayoutPanel1 in a form2. This is the code in which I create labels, a list and then add all of those labels to the TableLayOutPanel1:
Public Class Form2
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim lbl0, lbl1, lbl11, lbl2, lbl22, lbl3, lbl33, lbl4, lbl44, lbl5, lbl55, lbl6, lbl66, lbl7, lbl77 As New Label
lbl0.Text = "ACCESORIOS"
lbl0.Font = New System.Drawing.Font("MS Reference Sans Serif", 15.75, FontStyle.Bold)
lbl0.Location = New Point(110, 12)
lbl0.AutoSize = True
Me.Controls.Add(lbl0)
lbl1.Text = "Té 180°"
lbl11.Text = Te180
lbl2.Text = "Té 90° Empalme - Codo Triple"
If Global1 <> 0 Then
lbl22.Text = 0
Else
lbl22.Text = Global2 - 1
End If
lbl3.Text = "Soporte 90° T/T"
lbl33.Text = SoporteTT90
lbl4.Text = "Base para tubo de 1 1/2 - 3 agujeros"
lbl44.Text = Int(lbl11.Text) + Int(lbl22.Text) + (lbl33.Text)
lbl5.Text = "Base para tubo de 1 1/2 - 1 agujero"
lbl55.Text = 2
lbl6.Text = "Tapas para base de tubo de 1 1/2"
lbl66.Text = lbl44.Text
lbl7.Text = "Tornillos y Tarugos 5 x 50 y N°8 Ladrillo Hueco"
lbl7.Font = New System.Drawing.Font("MS Reference Sans Serif", 15.75, FontStyle.Bold)
lbl77.Text = (Int(lbl44.Text) + Int(lbl55.Text)) * 3
Dim labellist As New List(Of Label)()
labellist.Add(lbl1)
labellist.Add(lbl2)
labellist.Add(lbl3)
labellist.Add(lbl4)
labellist.Add(lbl5)
labellist.Add(lbl6)
labellist.Add(lbl7)
labellist.Add(lbl11)
labellist.Add(lbl22)
labellist.Add(lbl33)
labellist.Add(lbl44)
labellist.Add(lbl55)
labellist.Add(lbl66)
labellist.Add(lbl77)
Dim h = 0
For i = 0 To 1
For j = 0 To 6
Dim etiqueta As New Label
etiqueta.Text = labellist(h).Text
TableLayoutPanel1.Controls.Add(etiqueta, i, j)
h = h + 1
Next
Next
End Sub
End Class
The problem is that the the full label doesn't appear in the table.[enter image description here][1]
I have tried Autosizing the labels, the tablelayout. Nothing works. It's like there's an invisible line that doesn't let the text of the label get past a line in the table. Any help appreciated. Thanks.
The layout in form2. enter image description here
What happens when I make the font in the TLP 5pts. The whole label appears in two lines. enter image description here

Mainly, you create all those labels, store them in a list. Then all you use them for is to set the text on another new label you create to add to the controls collection.
Here is a shorter, simpler way to do all that with no extra list, and just one scratch label variable for the TLP set:
Dim texts = {"Te 180", "Te 90 - blah blah blah", "Soprte 90 T/T",
"Torillas y salsa", "Torillas y salsa y guacamole"}
Dim lbl As Label
For n As Int32 = 0 To texts.Length - 1
lbl = New Label
lbl.Text = texts(n)
' more important than autozise, probably:
lbl.Dock = DockStyle.Fill
' debug: to see the border for tweaking
lbl.BorderStyle = BorderStyle.FixedSingle
' add the one you created to the controls collection
tlp1.Controls.Add(lbl, 0, n)
Next

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)

Creating a chart in VisualBasic.net which has a Y axis comprising of string values

I'd like to create a chart in VB.net which has X and Y values in the form of a string.
Example below:
Sorry for the bad drawing, but this is what I'd like it to do
Can anybody help me find the settings to do this?
I can transfer data to a graph but it ends up looking like this:
This is what my current graph looks like. As you can see, I can't get the Y axis working.
(also dont worry about the X axis containing the grades, that's just something I need to fix. The grades string() still contains the right data)
This is a sample of my code: (don't worry about delimitegrades(), that just formats data for the grades into 'A', 'B', etc)
Subjects is a string() list.
Grades is an array which contains the data I need to insert. ChrtSubgrade is the chart itself.
Public Sub CreateGraph(ByVal name As String, subjects() As String)
MsgBox("Generating graph for " & name)
chrtSubgrade.Series.Clear()
chrtSubgrade.Series.Add("Data")
chrtSubgrade.Series(0).ChartType = DataVisualization.Charting.SeriesChartType.Column
chrtSubgrade.Series(0).YValueType = DataVisualization.Charting.ChartValueType.String
chrtSubgrade.Series(0).IsValueShownAsLabel = True
delimitgrades(subjects)
For i = 0 To subjects.Count - 2
chrtSubgrade.Series(0).Points.AddXY(subjects(i), grades(i))
Next
I've breakpointed all the code and the arrays and data transfer is fine so I believe it's just down to how I'm creating the graph.
I can't link the chart to a database since I'm drawing the source data from an XML file.
Thanks very much for any help you might be able to give.
I figured out a new method. Instead of using the VB charting tools I made my own. Here's the code:
Public Sub CreateGraph(ByVal name As String, subjects() As String)
delimitgrades(subjects) 'collects the info from subjects which contains the grade data and make a new array from it containing only grades
MsgBox("Generating graph for " & name)
Dim mygraphics As Graphics = Graphics.FromHwnd(hwnd:=ActiveForm.Handle) 'defines a new graphics set on the Grades window
Dim axespen As New Pen(Color.Black, 5) 'makes a pen so I can draw the axes
Dim Xaxisleft As New Point(30, 350) 'defines the left point of the X axis
Dim Xaxisright As New Point(400, 350) 'defines the right point of the X axis
Dim Yaxisbottom As New Point(30, 350) 'defines the bottom point of the Y axis
Dim yaxistop As New Point(30, 80) 'defines the top point of the Y axis
For i = 0 To 4 'for each possible grade - A* through D
Dim labelgrade As New Label 'makes a label
With labelgrade 'with said label
.BackColor = Color.Transparent 'makes its background colourless
.AutoSize = True 'resizes the bounding box
Select Case i 'examines I - the counting variable
Case Is = 0 ' if its 0
.Text = "A*" ' sets the labels text to A*
.Location = New Point(2, 100) 'moves it to the right place
Case Is = 1 'etc
.Text = "A"
.Location = New Point(2, 140)
Case Is = 2
.Text = "B"
.Location = New Point(2, 180)
Case Is = 3
.Text = "C"
.Location = New Point(2, 220)
Case Is = 4
.Text = "D"
.Location = New Point(2, 260)
End Select '/etc
End With
Controls.Add(labelgrade) 'inserts the label into the form
Next
For i = 0 To subjects.Count - 2 'the last part of the subjects array is empty so it counts to the last position containing data
Dim labelsubject As New Label 'makes a new label
Dim labelxoffset As Integer = 30 'defines the variable xoffset which is used to determine where all labels should be placed
With labelsubject 'with this label
.BackColor = Color.Transparent 'make the background colourless
.AutoSize = True 'resize the bounding box
Select Case i 'examine i
Case Is = 0 'if this is the first label placed onto the form
.Text = subjects(i) 'take the first entry in the subjects array
.Location = New Point(30, 355) 'place the label on the X axis in the first position
Case Else 'otherwise
.Text = subjects(i) 'take the right name from the array and make the label reflect this name
.Location = New Point(labelxoffset + (i * 70), 365) 'set its location depending on which place it is in the array using xoffset
End Select
End With
Controls.Add(labelsubject) 'add the label to the form
Next
'Axes
mygraphics.DrawLine(axespen, Xaxisleft, Xaxisright) 'create
mygraphics.DrawLine(axespen, Yaxisbottom, yaxistop) 'the axes
'bars
For i = 0 To grades.Count - 1 'from 0 to the second to last entry in the grades array (this is because of how I formed the grades array. It still works.
Dim grade As String = grades(i) 'create a temp variable to store the correct entry from the grades array
Dim gradeindex As Integer = Nothing ' create the index integer, this is used to determine how high the bar should go
Dim gradepen As New Pen(Color.Green, 50) 'make the pen for the bars
Dim p1 As New Point(30, 350) 'define point 1 as above the first label
Dim p2 As New Point 'create point 2
Dim x As Integer = (58 + (70 * i)) 'create a new xoffset integer
Dim yoffset As Integer = 348 ' create the yoffset integer. This is to place the bottom point of the bar correctly
Select Case grade 'examine grade
Case Is = "A*" 'if its A*
gradeindex = 100 'the top y coord is 100
p1 = New Point(x, yoffset) 'p1 is now x, yoffset
p2 = New Point(x, gradeindex) 'p2 is now x, gradeindex
Case Is = "A" 'etc
gradeindex = 140
p1 = New Point(x, yoffset)
p2 = New Point(x, gradeindex)
Case Is = "B"
gradeindex = 180
p1 = New Point(x, yoffset)
p2 = New Point(x, gradeindex)
Case Is = "C"
gradeindex = 220
p1 = New Point(x, yoffset)
p2 = New Point(x, gradeindex)
gradepen = New Pen(Color.Orange, 50) 'make the grade pen orange
Case Is = "D"
gradeindex = 260
p1 = New Point(x, yoffset)
p2 = New Point(x, gradeindex)
gradepen = New Pen(Color.Red, 50) 'make the grade pen red
End Select '/etc
mygraphics.DrawLine(gradepen, p1, p2) 'draw the line from p1 to p2
Next
End Sub
Here's the output for someone who has the following data: German;A* , Maths;A , French;A* , Bio;C , Bus(business for example);B
Output
Hope this helps anyone else having this issue. Thanks!

Arranging Buttons inside a Panel vb.net

I am trying to put 25 Buttons inside a Panel in VB.Net 2015 Classic Form Like the Picture but it is not working . could you please help... bellow my code
Dim i As Integer
For i = 1 To 25
newButton = New Windows.Forms.Button
newButton.AutoSize = True
newButton.Name = "btnButton" & i
newButton.Text = "Button " & i
newButton.Top = i * 5
newButton.Left = i * 25
newButton.Size = New Size(95, 70)
AddHandler newButton.Click, AddressOf ButtonClicked
Panel1.Controls.Add(newButton)
Next
Your code is creating the buttons, and the problem is that they are not arranged properly so what you need to do is arrange them in rows and columns. here i help you to do this;
Here this snippet will tell you how to arrange them in 5 columns and n rows:
Dim x As Integer = 5 ' x co-ordinate of the point
Dim y As Integer = 5 ' y co-ordinate of the point
For i = 1 To 25
If i Mod 5 = 0 Then ' For starting next row after column
y += 100 ' 100 is not mandatory change as per size of button
x = 0
Else
x += 100 ' 100 is not mandatory change as per size of button
End If
Dim p As Point = New Point(x, y)
Dim newButton = New Windows.Forms.Button
newButton.Location = p
//do the rest of formatting here
Panel1.Controls.Add(newButton)
Next

vb.net layering of controls not working properly

I simply want to add three controls to my form. The first two show up, but the third does not. I do not understand why this behavior is happening. I have tried using .bringToFront(), but I end up with the same results. I also tried using Me.controls.setChildIndex() but that does not help either.
I am at a loss. I must be doing something wrong. Please help.
Thanks.
This is my code:
' Add the label
' ------------------
Dim menu_label As New Label
menu_label.Text = "Menu"
menu_label.Location = New Point(50, 20)
menu_label.Width = 50
menu_label.Font = New Font(main_font, main_font_size, FontStyle.Regular)
menu_label.ForeColor = Color.White
Me.Controls.Add(menu_label)
' create the image
' ---------------
Dim logo As New PictureBox
Dim logo_image As Image
logo_image = My.Resources.logo
logo.Image = logo_image
logo.Width = 30
logo.Height = 30
logo.Left = 5
logo.Top = 0
Me.Controls.Add(logo)
' add a line
' ----------
Dim line As New Panel
line.Height = 1
line.Width = Me.Width
line.BackColor = Color.Red
line.Location = New Point(0, 32)
Me.Controls.Add(line)
' end code
' ---------------------------------
Only the first two items show up no matter which order I put them in. So I either get just the logo and the menu label, or just the logo and the line, or just the line and the menu label. It's nuts!
So I tried:
Me.Controls.SetChildIndex(logo, 0)
Me.Controls.SetChildIndex(menu_label, 1)
Me.Controls.SetChildIndex(line, 2)
Whichever item gets assigned to level 2 never shows up.
I also tested and it worked fine for me. Changed the form backcolor to black so you can see the results better:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
' Add the label
' ------------------
Dim menu_label As New Label
menu_label.Text = "Menu"
menu_label.Location = New Point(50, 20)
menu_label.Width = 50
'menu_label.Font = New Font(main_font, main_font_size, FontStyle.Regular)
menu_label.ForeColor = Color.White
Me.Controls.Add(menu_label)
' create the image
' ---------------
Dim logo As New PictureBox
Dim logo_image As Image
'logo_image = My.Resources.logo
'logo.Image = logo_image
logo.BackColor = Color.Yellow
logo.Width = 30
logo.Height = 30
logo.Left = 5
logo.Top = 0
Me.Controls.Add(logo)
' add a line
' ----------
Dim line As New Panel
line.Height = 1
line.Width = Me.Width
line.BackColor = Color.Red
line.Location = New Point(0, 32)
Me.Controls.Add(line)
Me.BackColor = Color.Black
End Sub
What else is on your form? Perhaps you could post a screenshot?

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.