Can't Refresh DataGridView on TabControl Page When There are More Columns Added to DataGridView - vb.net

There is a DataGridView spawned dynamically and a TabControl is assigned as a parent. The DataGridView is populated with random numbers. While there are no problems with headers or cell values, I can't seem to be able to resize the DataGridView on the tab control page when more columns are added dynamically.
Is there an issue with the Parent scoping for the TabControl, that prevents regeneration and display of more columns on the TabControl, once everything is refreshed?
Dim datagridview1 As New DataGridView
Datagridview1.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders)
Dim dgvColumnHeaderStyle As New DataGridViewCellStyle()
dgvColumnHeaderStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
Datagridview1.ColumnHeadersDefaultCellStyle = dgvColumnHeaderStyle
Datagridview1.AllowUserToAddRows = False
Datagridview1.ScrollBars = ScrollBars.Both
DataGridView1.Font = New System.Drawing.Font("Lucida Sans Typewriter", 8)
For j As Integer = 1 To UBound(columnheaders)
DataGridView1.Columns.Add(columnheaders(j), columnheaders(j))
Next
For j As Integer = 1 To UBound(columnheaders)
DataGridView1.Columns(columnheaders(j)).HeaderText = columnheaders(j)
Next
For i As Integer = 0 To UBound(rowheaders) - 1
Dim n As Integer = DataGridView1.Rows.Add()
For j = 0 To UBound(columnheaders) - 1
DataGridView1.Rows.Item(n).Cells(j).Value = Rnd()
If i Mod 2 = 0 Then DataGridView1.Rows.Item(i).Cells(j).Style.BackColor = Color.White
If i Mod 2 <> 0 Then DataGridView1.Rows.Item(i).Cells(j).Style.BackColor = Color.AliceBlue
Next
Next
Datagridview1.Visible = True
Datagridview1.Height = Me.Height - 100
Datagridview1.Width = Me.Width - TabControl2.Left - 100
Datagridview1.Parent = TabControl2.TabPages(1)
TabControl2.TabPages(1).Refresh()
TabControl2.Refresh()
Datagridview1.Refresh()

RESOLVED: It worked out that any time you programatically add a datagridview to a tabcontrol, if you update (recreate) the datagridview and want to see the new datagridviw on the same tabcontrol page, you have to clear the controls on the tab page. Following gives an example for using a TabControl1 control and page 0, i.e., the first tab:
Me.TabControl1.SelectedTab = TabControl2.TabPages.Item(0)
Me.TabControl1.TabPages(0).Controls.Clear()
Me.TabControl1.TabPages(0).Controls.Add(datagridview1)

Related

Unexpected TableLayoutPanel Behavour

Hi having some issues with some nested tablelayoutpanels in a custom control
I have a tablelayoutpanel in a tablelayoutpanel in a tablelayoutpanel Crazy i know but it keeps it uniform and ordered
The custom control consists of 2 tablelayoutpanels that is placed in a table layout panel on a form and in a preview area of my main form.
Having them set at design time works fine but dynamically adding / removing the topmost ones with 1 row 2 columns into the one below it that has 1 column and x rows only Seems to break the autosizing behavior I'm chasing.
So I want the cells & rows to resize automatically based on the contents in this case labels but still remain in a neat ordered layout
There's no docking anywhere in the hierarchy of controls just anchors here and there
Here's my code to add the tablelayoutpanels below
"https://i.stack.imgur.com/vRfhE.png"
Private Sub AddControl(ByRef Counter As Counter)
Dim Gpanel As New TableLayoutPanel
Dim tlabel As New Label
Dim clabel As New Label
Dim pad As Integer = Counter.Cpad
TLPanel.AutoSizeMode = AutoSizeMode.GrowAndShrink
Gpanel.AutoSizeMode = AutoSizeMode.GrowAndShrink
Gpanel.AutoSize = True
Gpanel.GrowStyle = TableLayoutPanelGrowStyle.AddRows
Gpanel.BorderStyle = BorderStyle.FixedSingle
Gpanel.CellBorderStyle = TableLayoutPanelCellBorderStyle.Inset
TLPanel.BorderStyle = BorderStyle.FixedSingle
Gpanel.Dock = DockStyle.None
Gpanel.Padding = New Padding(0)
Gpanel.Anchor = AnchorStyles.Top Or AnchorStyles.Left
Gpanel.BackColor = Color.Transparent
Gpanel.RowCount = 1
Gpanel.ColumnCount = 2
Gpanel.RowStyles.Add(New RowStyle(SizeType.AutoSize))
Gpanel.ColumnStyles.Add(New ColumnStyle(SizeType.AutoSize))
Gpanel.ColumnStyles.Add(New ColumnStyle(SizeType.AutoSize))
tlabel.Dock = DockStyle.None
clabel.Dock = DockStyle.None
tlabel.GetPreferredSize(Size.Empty)
clabel.GetPreferredSize(Size.Empty)
tlabel.Text = Counter.Clabel
clabel.Text = Counter.Ccount.ToString
tlabel.Padding = New Padding(pad)
clabel.Padding = New Padding(pad)
tlabel.Anchor = AnchorStyles.None
clabel.Anchor = AnchorStyles.None
tlabel.ForeColor = Color.FromName(Counter.Clcolor)
clabel.ForeColor = Color.FromName(Counter.Ccolor)
Dim fontstyle As New FontStyle
fontstyle = Counter.ClfontStyle
tlabel.Font = New Font(Counter.Clfont, Counter.Clfontsize, fontstyle)
fontstyle = Counter.CcfontStyle
clabel.Font = New Font(Counter.Ccfont, Counter.Ccfontsize, fontstyle)
Gpanel.Controls.Add(tlabel, 0, 0)
Gpanel.Controls.Add(clabel, 1, 0)
TLPanel.Controls.Add(Gpanel, 0, Counter.ID)
TLPanel.RowCount += 1
TLPanel.RowStyles.Add(New RowStyle(SizeType.AutoSize))
Dim Styles As TableLayoutRowStyleCollection = TLPanel.RowStyles
Dim Cstyles As TableLayoutColumnStyleCollection = Gpanel.ColumnStyles
Gpanel.RowStyles.Item(0) = New RowStyle(SizeType.AutoSize)
TLPanel.ColumnStyles.Item(0) = New ColumnStyle(SizeType.AutoSize)
For i = 0 To Cstyles.Count - 1
Cstyles.Item(i) = New ColumnStyle(SizeType.AutoSize)
Next
For i = 0 To Styles.Count - 1
Styles.Item(i) = New RowStyle(SizeType.AutoSize)
Next
TLPanel.CellBorderStyle = TableLayoutPanelCellBorderStyle.Inset
AutoSize = True
AutoSizeMode = AutoSizeMode.GrowAndShrink
End Sub
'

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)

autoresizing column header in visual basic datagridview

I've been trying to resize the header column in my program as it cuts off an important row label. AutoSizeColumnsMode and AutoResizeColumns() doesn't work. All my attempts so far have lead to the other columns been resized, however not the header column.Image of form
Dim dgv_flightTemplate As New DataGridView
Dim c As Integer = txb_columns.Text
Dim r As Integer = txb_rows.Text
For colcount As Integer = 0 To c - 1
Dim nc As New DataGridViewTextBoxColumn
nc.Name = "Seating Column"
dgv_flightTemplate.Columns.Add(nc)
Next
dgv_flightTemplate.Rows.Add(r)
dgv_flightTemplate.Rows(0).HeaderCell.Value = "A -"
Me.Controls.Add(dgv_flightTemplate)
dgv_flightTemplate.Location = New Point(400, 400)
dgv_flightTemplate.AllowUserToAddRows = False
dgv_flightTemplate.AllowUserToDeleteRows = False
dgv_flightTemplate.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells
dgv_flightTemplate.AutoResizeColumns()
also note this has to be done programmatically because i am creating the datagridview from the size the user gives
Thanks for any replies,
Taine

Fitting runtime buttons inside a form

I have a number of buttons between 5-20 and it's variable each time the form loads based on the user settings. I am trying to fit all these buttons on my form no matter what the size of the form is. The buttons are generated during runtime. I would like the first button to be 20 points from the top bar (at any size) and the rest of the buttons simply to fit in the form. This is what I have now but I have to maximize the form to view them all and also while I'm expanding the form the space between the buttons decreases and they overlap with each other whereas they should keep a relative distance. Any ideas?
Dim iButtonWidth, iButtonHeight, iVerticalSpace As Integer
If UserButtons.Count > 0 Then
iButtonHeight = Me.Size.Height - (Me.Size.Height * 0.85)
iButtonWidth = Me.Size.Width - (Me.Size.Width * 0.5)
iVerticalSpace = iButtonHeight / 3
For Each btn In UserButtons
btn.Size = New System.Drawing.Size(iButtonWidth, iButtonHeight)
btn.Location = New Point(20, 20 + btn.TabIndex * iVerticalSpace * 3)
Next
End If
Here's a quick example using the TableLayoutPanel to play with:
Public Class Form1
Private UserButtons As New List(Of Button)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Static R As New Random
Dim NumButtons As Integer = R.Next(5, 21) ' "a number of buttons between 5-20 and it's variable each time"
UserButtons.Clear()
For i As Integer = 1 To NumButtons
Dim btn As New Button()
btn.Text = i.ToString("00")
btn.Dock = DockStyle.Fill ' Optional: See how you like it with this on vs. off
UserButtons.Add(btn)
Next
DisplayButtons()
End Sub
Private Sub DisplayButtons()
TableLayoutPanel1.SuspendLayout()
TableLayoutPanel1.Controls.Clear()
TableLayoutPanel1.ColumnStyles.Clear()
TableLayoutPanel1.ColumnCount = 5 ' Fixed Number of Columns
For i As Integer = 1 To TableLayoutPanel1.ColumnCount
TableLayoutPanel1.ColumnStyles.Add(New ColumnStyle(SizeType.Percent, 911)) ' the size doesn't matter here, as long as they are all the same
Next
' Variable Number of Rows:
Dim RowsRequired As Integer = ((UserButtons.Count - 1) \ TableLayoutPanel1.ColumnCount) + 1 ' Integer Division
TableLayoutPanel1.RowStyles.Clear()
TableLayoutPanel1.RowCount = RowsRequired
For i As Integer = 1 To TableLayoutPanel1.RowCount
TableLayoutPanel1.RowStyles.Add(New RowStyle(SizeType.Percent, 911)) ' the size doesn't matter here, as long as they are all the same
Next
TableLayoutPanel1.Controls.AddRange(UserButtons.ToArray)
TableLayoutPanel1.ResumeLayout()
End Sub
End Class
First of all what kind of container are the buttons in? You should be able to set the container's AutoScroll property to true - then when controls within it spill out of the visible bounds you will get a scroll bar.
Then also what you could do is draw each button in more of a table with a certain number next to each other before dropping down to the next line (instead of just 1 button on each line). If that is an option that works for you then you could get more buttons within the visible space.
I happen to have an example to do the same thing with picture boxes (and text boxes under each picture box). Hope this helps:
Dim point As New Point(0, 0)
'create 11 picture and text boxes-you can make this number the number your user selects.
Dim box(11) As PictureBox
Dim text(11) As TextBox
Dim i As UInt16
For i = 0 To 11 'or whatever your number is
box(i) = New PictureBox
box(i).Width = 250 'your button width
box(i).Height = 170 'your button height
box(i).BorderStyle = BorderStyle.FixedSingle
box(i).Location = point
layoutsPanel.Controls.Add(box(i)) 'my container is a panel
text(i) = New TextBox
text(i).Height = 50
text(i).Width = 250
point.Y += box(i).Height
text(i).Location = (point)
layoutsPanel.Controls.Add(text(i))
point.Y -= box(i).Height 'reset Y for next picture box
'Put 4 picture boxes in a row, then move down to next row
If i Mod 4 = 3 Then
point.X = 0
point.Y += box(i).Height + text(i).Height + 4
Else
point.X += box(i).Width + 4
End If
Next

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.