How to re-arrange multiple buttons within a panel when panel/form is resized? - vb.net

I have a vb.net form that has a panel. Inside the panel, there are 40 buttons dynamically created (see code below). If user wants to resize the form, the panel will resize, but the button layout will not change (i.e. 5 columns of buttons instead of 4 when the form expands horizontally. Is there any way to make the buttons automatically arrange, like when user make the form smaller, there are only 3, or 2, or 1 columns of buttons, and when the form is getting larger, the buttons will arrange to 5 or more columns?
Here is the code of the form, and what I have done so far:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim a, b As Integer
For i = 0 To 40
Dim SampleButton As New Button With {
.Name = "Sample_Button" & "-" & i.ToString,
.Text = "Sample_Button" & "-" & i.ToString,
.Location = New Point(a, b),
.Font = New Font("Segoe UI", 11, FontStyle.Regular),
.Height = 50,
.Width = 180,
.FlatStyle = FlatStyle.Flat,
.TextAlign = ContentAlignment.MiddleCenter,
.Cursor = Cursors.Hand
}
a += SampleButton.Width + 10
If (a + SampleButton.Width) > Panel_MainMenu.Width Then
a = 10
b += SampleButton.Height + 10
End If
SampleButton.BackColor = Color.FromArgb(255, 232, 251, 232)
Panel_MainMenu.Controls.Add(SampleButton)
Next
End Sub
Private Sub Panel_MainMenu_Layout(sender As Object, e As LayoutEventArgs) Handles Panel_MainMenu.Layout
'For Each Controls In Panel_MainMenu.Controls
'Next
End Sub
End Class
What I have done:
Anchor Panel_MainMenu to top, left, right, and bottom (it helps resize the panel according to the size of the form, but not the buttons within it)
Panel_MainMenu.AutoScroll = True
Panel_MainMenu.AutoSize = False and Panel_MainMenu.AutoSizeMode = GrowOnly
I searched on Google on how to use Panel.Layout, but I have not figured out a way to parse the button layout to Panel.Layout to let them adjust accordingly.
I set Panel_MainMenu's minimum size to 776, 426
Any help would be greatly appreciated. Thanks for reading my post!

Simply change from using a Panel to a FlowLayoutPanel:
Represents a panel that dynamically lays out its contents horizontally
or vertically.
You will then not need to specify a Location for each button since this will be taken care of for you.
Anchor/Dock the FlowLayoutPanel so that it resizes with the form, then the buttons will automatically be arranged.

Related

Rows Added to a Datagridview not being captured in Screen Capture

I am running into an issue where I am attempting to add some blank rows to a datagridview before printing the form for use.
I am having an issue trying to understand where I need to put the code to add the rows to the data gridview so they are added and captured before the user hits print. My concern is that I am not adding the rows in the right spot before the screen is captured however the code to add the rows is run before the code to hide the buttons is implemented however the buttons are removed and the rows are not added in the actual printed image.
If that is not clear hopefully these images will make more sense. At this point I am not sure why the buttons being hidden are being captured but the added rows are not when based on the code it looks like the rows are being added before the buttons are hidden.
Thank you.
Here is the Image before the user hits print
Here is the Image after the user hits Print
And here is what actually printed
And here is the code in question that captures the screen
Private Sub CaptureScreen()
Dim myGraphics As Graphics = Me.CreateGraphics()
Dim s As Size = Me.Size
If dgvReceive.Rows.Count < 27 Then
Dim rowstoadd As Integer = 0
rowstoadd = 27 - dgvReceive.Rows.Count
dgvReceive.Rows.Add(rowstoadd)
End If
If MemoryImage IsNot Nothing Then
MemoryImage.Dispose()
End If
MemoryImage = New Bitmap(s.Width, s.Height, myGraphics)
For Each btn As Button In Me.Controls.OfType(Of Button)
btn.Visible = False
Next
dgvReceive.ClearSelection()
lblTitle.Select()
Me.FormBorderStyle = FormBorderStyle.None
Dim memoryGraphics As Graphics = Graphics.FromImage(MemoryImage)
memoryGraphics.CopyFromScreen(Me.Location.X, Me.Location.Y, 0, 0, s)
Me.FormBorderStyle = FormBorderStyle.Sizable
For Each btn As Button In Me.Controls.OfType(Of Button)
btn.Visible = True
Next
End Sub

winforms: Slow performance on form load

I have a VB.NET winforms application. One of its forms, contains a flowlayoutpanel which I populate dynamically (programmatically) on form load event with pairs of label-textbox. My flowlayoutpanel is created in design time with all the properties set to default except below ones:
AutoSize: true
AutoScroll: true
Dock: fill
FlowDirection: TopDown
Then I populate it using below code within the form load event:
Private Sub MyForm_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
Dim lbl As Label
Dim txt As TextBox
Dim flowLayout As FlowLayoutPanel
Dim g As Graphics
For i As Integer = 0 To 253
lbl = New Label
lbl.Text = i.ToString("000") + ":"
lbl.Anchor = AnchorStyles.None
lbl.AutoSize = True
txt = New TextBox
txt.Text = "<" + i.ToString.PadLeft(3, " ") + ">"
txt.MaxLength = 5
txt.Anchor = AnchorStyles.None
txt.ReadOnly = True
g = txt.CreateGraphics
txt.Width = g.MeasureString(txt.Text, txt.Font).Width + 5
g.Dispose()
flowLayout = New FlowLayoutPanel
flowLayout.FlowDirection = FlowDirection.LeftToRight
flowLayout.AutoSize = True
flowLayout.Anchor = AnchorStyles.None
flowLayout.Margin = New Padding(0)
flowLayout.Padding = New Padding(0)
flowLayout.Controls.Add(lbl)
flowLayout.Controls.Add(txt)
Me.FlowLayoutPnl.Controls.Add(flowLayout)
Next
End Sub
As I have stated above FlowLayoutPnl is created on design time and components on this are added following TopDown flow direction.
Above code produces this result.
The problem here is that on opening this form it takes so much time (a few seconds) to open because it is doing all the stuff in form load event. It takes 35 seconds to open!. When all the stuff is done then form becomes visible after 35 seconds...
So I would like to know if there is some kind of method to speed up form load. I have read some posts here saying about implement and show some kind of splash screen while it loads indicating user that it is being loaded or even perform an asynchronous load. What about creating a background thread from form load event in order to do this stuff? Anyone could guide me in the right direction? A very little example will be highly appreciated. How this kind of problems are normally resolved?

How to get Winforms Panel to correctly layout many items?

I've got a WinForms Panel control which holds a large number of child controls. Each child is left docked, causing the horizontal width of the contents to grow. The containing Panel has its AutoScroll property set so that you can get to all the contents.
I'm running into a problem when the total width of the contents gets too large. Once you've hit this maximum width, additional content elements are placed on top of existing contents instead of being placed to the right. But, if I resize the Panel after it has done its initial layout, it corrects itself by expanding its logical width and placing each content element in the correct location. How do I get it to layout correctly before the user resizes the window?
Here's a simple example:
Form1.vb
Public Class Form1
Protected Overrides Sub OnLoad(e As EventArgs)
MyBase.OnLoad(e)
For i As Integer = 1 To 200
Dim gb As New GroupBox
gb.Text = "Box " & i.ToString
gb.Width = 250
gb.Dock = DockStyle.Left
Panel1.Controls.Add(gb)
gb.BringToFront()
Next
End Sub
End Class
Form1.Designer.vb
Partial Class Form1
Inherits System.Windows.Forms.Form
Private Sub InitializeComponent()
Me.Panel1 = New System.Windows.Forms.Panel()
Me.SuspendLayout()
'
'Panel1
'
Me.Panel1.AutoScroll = True
Me.Panel1.Dock = System.Windows.Forms.DockStyle.Fill
Me.Panel1.Location = New System.Drawing.Point(0, 0)
Me.Panel1.Name = "Panel1"
Me.Panel1.Size = New System.Drawing.Size(284, 262)
Me.Panel1.TabIndex = 0
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(284, 262)
Me.Controls.Add(Me.Panel1)
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)
End Sub
Friend WithEvents Panel1 As System.Windows.Forms.Panel
End Class
This is what the window looks like when it first comes up, scrolled nearly to the end so you can see the problem area. Notice that Box 183 to 199 are missing because they are placed on top of each other. This is not right.
This is what the window looks like after you manually resize it, scrolled nearly to the end. The panel fixed itself in response to the resize; the total logical width of the panel was automatically extended enough to hold all the contents. This is what I want it to look like when it first comes up.
I've tried manually setting the location of each box, and I've tried calling PerformLayout() and several other functions. Nothing seems to work. So far I haven't found the magic combination to get the good layout. Does anyone know how to fix this?
Edit:
Here's a screenshot that might make the issue more obvious. I adjusted the box widths and the number of boxes to show the problem better. See how the last box overlaps box 656? Every box from 657 to 700 has the same incorrect location. Turning off docking and setting the location myself doesn't help.
Looks like a bug with the scrolling information. If you call PerformLayout when the Panel is scrolled all the way to the right, it correctly places the controls in the proper place. That requires some code in the OnShown method:
Protected Overrides Sub OnLoad(e As EventArgs)
MyBase.OnLoad(e)
Panel1.AutoScroll = True
Panel1.SuspendLayout()
For i As Integer = 1 To 200
Dim gb As New GroupBox
gb.Text = "Box " & i.ToString
gb.Width = 250
gb.Dock = DockStyle.Left
Panel1.Controls.Add(gb)
gb.BringToFront()
Next
Panel1.ResumeLayout(False)
End Sub
Protected Overrides Sub OnShown(e As EventArgs)
MyBase.OnShown(e)
Panel1.AutoScrollPosition = New Point(Panel1.HorizontalScroll.Maximum - _
Panel1.HorizontalScroll.LargeChange, 0)
Panel1.PerformLayout()
Panel1.AutoScrollPosition = Point.Empty
End Sub
Of course, having over 200 container controls on the form is never recommended.
AutoScroll is not AutoPositionMyChildren. From MSDN:
When adding controls programmatically to a form, use the AutoScrollPosition property to position the control either inside or outside of the current viewable scroll area.
If you looped thru the controls, to print their location, you's see at some point (probably around 130) that Location.Y becomes fixed at 32767 probably some default unscrolled max. This is also the point they start stacking because they in fact have the same initial location. Some of the code you have makes up for that but it isnt quite right. Once you scroll it, the panel fixes the coords on the child controls.
First, I would suggest that you set Panel1.AutoScrollMinSize to something like {480, 0} so that the HScroll bar appears at design time; this allows you to calc a good height for the boxes which wont cause a VScroll as you add controls.
Dim gb As GroupBox
' only 150 because problem is when (i * width) > 32k
For i As Integer = 0 To 150
gb = New GroupBox
gb.Name = i.ToString ' added
gb.Text = "Box " & i.ToString
gb.Width = 250
' no docking so set the height
gb.Height = Panel1.Bounds.Height - 30 ' trying to avoid the VSCroll
' set location explicitly
gb.Location = NewCtlLocation(Panel1.Controls.Count,
Panel1.AutoScrollPosition.X)
' Dock and Anchor mess up the AutoScroll
'gb.Dock = DockStyle.Left
Panel1.Controls.Add(gb)
' allow panel to update its scroll positions
Panel1.ScrollControlIntoView(gb)
' not needed; seems to offset something with Dock
' changing ZOrder may not always be desirable
'gb.BringToFront()
' debug illumination
Console.WriteLine("{0} {1} {2}", i.ToString,
Panel1.AutoScrollPosition.X.ToString,
gb.Location.X.ToString)
Next
'Go back to start
Panel1.ScrollControlIntoView(Panel1.Controls("0"))
Location helper so you can tweak gutters or margins (dock replacement):
Friend Function NewCtlLocation(ByVal n As Integer,
ByVal ScrollPosX As Integer) As Point
Const TopMargin As Integer = 5
Const LeftMargin As Integer = 5
Return New Point((n * 250) + ScrollPosX, 0)
End Function
Notes:
I have a vertical scroller which repeatedly adds up to 120 user controls which works well but it does not need/use ScrollControlIntoView and they never stack up like yours do. I suspect maybe because they are smaller. There is also at least a second or two before the next one can be added, which may matter. But, good to know.
It might be possible to use the ControlAdded event of the panel to do something, but it would likely amount to ScrollControlIntoView. Doing it once at the end only doesnt work, so using it as they are added is allowing something to get updated as you go.
With the right fiddling, you might be able to get Dock to work, but I suspect it may be part of the problem such as Height and Left set this way dont update the panel's internal scroll map.
Your boxes actually look narrower than 250 - is autosize on?
Suspend/Resume Layout hurt rather than help - they prevent the control from doing anything about the virtual area being populated. It should happen fast enough that no one will see anything. Results:
Works on My SystemTM

VB.Net 2008 Buttons acts as Tab Controls

I am looking for a way to design things differently in my project. Instead of using TabControls I wish to use Buttons (Instead of pressing the tabs on the top I would like to press the Buttons on the left-side). These buttons when pressed they have their own Panel where each has their own respective content.
Select Case tabAdmin.SelectedIndex
Case 0
If txtCode_Patient.Text = "" Then
txtCode_Patient.Focus()
Else
cmdAdminister.Focus()
End If
Case 1
If txtD_Patient.Text = "" Then
txtD_Patient.Focus()
Else
cmdRefresh.Focus()
End If
Case 2
If txtI_Patient.Text = "" Then
txtI_Patient.Focus()
Else
cmdI_CUser.Focus()
End If
Case 3
If txtStat_CS.Text = "" Then
txtStat_CS.Focus()
Else
cmdStat_Refresh.Focus()
End If
End Select
The code above is similar to what my project acts and it works with TabControls. I want to do a similar thing but this time, like I said before, pressing Buttons on the left-side. How can I do a similar thing ?
UPDATE:
I found a way for this one but now my concern is how do I make it look like one of its default button 3D look-alike?
Public Class Tab
Inherits TabControl
Private Property DoubledBuffered As Boolean
Sub New()
SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.OptimizedDoubleBuffer Or ControlStyles.ResizeRedraw Or ControlStyles.UserPaint, True)
DoubledBuffered = True
SizeMode = TabSizeMode.Fixed
ItemSize = New Size(30, 110)
End Sub
Protected Overrides Sub CreateHandle()
MyBase.CreateHandle()
Alignment = TabAlignment.Left
End Sub
Protected Overrides Sub OnPaint(e As System.Windows.Forms.PaintEventArgs)
Dim B As New Bitmap(Width, Height)
Dim G As Graphics = Graphics.FromImage(B)
G.Clear(Color.AliceBlue)
For i = 0 To TabCount - 1
Dim TabRectangle As Rectangle = GetTabRect(i)
If i = SelectedIndex Then
'//Selected
G.FillRectangle(Brushes.DarkSlateGray, TabRectangle)
Else
'//Not Selected
G.FillRectangle(Brushes.AntiqueWhite, TabRectangle)
End If
G.DrawString(TabPages(i).Text, Font, Brushes.Black, TabRectangle, New StringFormat With {.Alignment = StringAlignment.Center, .LineAlignment = StringAlignment.Center})
Next
e.Graphics.DrawImage(B.Clone, 0, 0)
G.Dispose() : B.Dispose()
MyBase.OnPaint(e)
End Sub
End Class
Use the CheckBox control instead of Button, but set Appearance = Button, that way it looks exactly like a button can remains in the "pressed" state when clicked.
To shift between content, put each of your sub-forms into their own UserControl instances, then host them within a Panel control, then switch the .Visibility property of each sub-form according to which CheckBox was clicked.
There is an Outlook-style side bar available on Code Project. It has a VB version as well as C# and although it's knocking on a bit now, you could always adapt this to look a bit nicer. I have used it in the past and it worked pretty well as I recall.
You can set the selected tab via tabAdmin.SelectedIndex = 0 (or 1, 2, etc, but remember it is 0 based)
You may also set the tab by the tab's name via tabAdmin.SelectedTab = TabName
Use a common click event handler for the buttons. Store the relevant tabindex in the Tag property of the buttons. Then tabAdmin.SelectedIndex equals the tag of the clicked button cast as integer.

Order of controls being added to panel, control not showing unless docked

I imagine this is probably an easy to answer question but for some reason I can't get it to work
Sub New(ByVal Sess As AudioSessionControl2)
S_Session = Sess
'Create the panel and position it.
S_Panel.BackColor = Color.AliceBlue
S_Panel.Width = 200
S_Panel.Height = 40
Dim Position As New Point(6, 19)
If G_AppSessions.Count > 0 Then
Position = Point.Add(G_AppSessions.Item(G_AppSessions.Count - 1).SessionPanel.Location, New Point(0, 45))
End If
S_Panel.Location = Position
'Create a label which has the name of the process
Dim S_PName As New Label
S_PName.Text = "Test"
S_PName.Dock = DockStyle.Left
S_Panel.Controls.Add(S_PName)
'Create a button to change volume
Dim S_Save As New Button()
S_Save.Text = "Save"
AddHandler S_Save.Click, AddressOf Save_Click
S_Save.Parent = S_Panel
S_Panel.Controls.Add(S_Save)
S_Volume.Parent = S_Panel
S_PName.Parent = S_Panel
MainForm.Controls.Add(S_Panel)
S_Panel.Parent = MainForm.gb_Applications
End Sub
The problem is that, the label will show because its docked, but the button won't. It will only show if its docked as well, and thats just not what I want. This is part of a class for creating a dynamic UI, where I can create a number of this class to create a bunch of panels for various things.
I don't see anywhere where you are setting the label or button position. You probably have them both at 0,0 and the label is on top of the button, obscuring it. Did you try setting the position of both the controls, making sure they don't overlap?