How to resize a chart before printing in vb.net - vb.net

I would like to print a chart in my vb.net application but when I print it, it's very small and I can't find how to resize it.
For now, I'm using this code: (Found here : Some msdn printing subject)
Private Sub BT_Print_Click(sender As Object, e As EventArgs) Handles BT_Print.Click
Dim pdS As New PrintDocument()
AddHandler pdS.PrintPage, AddressOf pds_PrintPage
pdS.DefaultPageSettings.Landscape = True
Dim PrintDialog1 As New PrintPreviewDialog
PrintDialog1.Document = pdS
If (PrintDialog1.ShowDialog = DialogResult.OK) Then
Chart_Requis.Printing.PrintDocument.DefaultPageSettings.Landscape = True
pdS.Print()
End If
End Sub
Private Sub pds_PrintPage(sender As Object, ev As PrintPageEventArgs)
Dim chartPosition As New Rectangle(1, 1, ev.MarginBounds.Width, ev.MarginBounds.Height)
Chart_Requis.Printing.PrintPaint(ev.Graphics, chartPosition)
End Sub
After all my attempt I just reached to move margins... which is good but I still cannot read my chart correctly...
Do someone had the same issue and found a solution ?
----------------------------------------EDIT-------------------------------------
As I explain it the comment of your answer, I now can change chart's position and size but blank squares appears and I don't know why !

By image you have posted seems your issue is ChartArea not Chart Control.
You need to increase Area of your Chart Area.
In the example below (which can help you in that) I have used two parameters scaleX and scaleY .
You can work on those two to find the right size becomes on print.
Note that.: As Chart Area in the example I’ve used the first of your Chart Control, but, you can use another calling it by name. Hope is what you needs.
Private Sub BT_Print_Click(sender As Object, e As EventArgs) Handles BT_Print.Click
Using pdS As New PrintDocument()
Dim scaleX As Single = 1.5
Dim scaleY As Single = 1.2
With pdS.DefaultPageSettings
.Landscape = True
.Margins = New Margins(10, 10, 10, 10)
End With
Chart_Requis.Printing.PrintDocument = pdS
AddHandler pdS.PrintPage, Sub(obj As Object, ev As PrintPageEventArgs)
Using ev.Graphics
With Chart_Requis.ChartAreas.FirstOrDefault
Dim initialP As DataVisualization.Charting.ElementPosition = .Position
Dim newP As Rectangle = New Rectangle With {
.X = CInt(initialP.X),
.Y = CInt(initialP.Y),
.Width = CInt(initialP.Width * scaleX),
.Height = CInt(initialP.Height * scaleY)
}
.Position.FromRectangleF(newP)
Chart_Requis.Printing.PrintPaint(ev.Graphics, ev.MarginBounds)
.Position = initialP
End With
End Using
End Sub
Using PrintDialog1 As New PrintPreviewDialog With {
.Document = pdS
}
If (PrintDialog1.ShowDialog = DialogResult.OK) Then
pdS.Print()
End If
End Using
End Using
End Sub

Ok, I finally found something which worked for me here and I adapt it to my case : Another Stackoverflow subject
I let you see the final chart here :
I add a dialogbox to choose the printer and adapt a bit the original code as you can see here :
Private Sub BT_Print_Click(sender As Object, e As EventArgs) Handles BT_Print.Click
Print_Preview()
End Sub
Public Sub Print_Preview()
Dim Print_Doc As PrintDocument
Print_Doc = Chart_Requis.Printing.PrintDocument
AddHandler Print_Doc.PrintPage, New PrintPageEventHandler(AddressOf Print_Page)
'SHEET PARAMETERS
Print_Doc.DefaultPageSettings.Landscape = True
Print_Doc.DefaultPageSettings.Margins = New Printing.Margins(0, 1, 1, 1)
Print_Doc.DefaultPageSettings.Color = True
'CHOOSING PRINTER AND OTHER PARAMETERS
Dim Print_dlg As New PrintDialog
Print_dlg.Document = Print_Doc
Dim result As DialogResult = Print_dlg.ShowDialog()
'IF DIALOGBOX OK THEN CONTINUE OTHERWISE NO
If (result = DialogResult.OK) Then
'PUT MARKERS TO THE RIGHT SIZE
For i = 0 To Chart_Requis.Series.Count - 1
Chart_Requis.Series(i).MarkerSize = 1
Next
'CHECKING BEFORE PRINTING
Chart_Requis.Printing.PrintPreview()
End If
End Sub
Private Sub Print_Page(ByVal sender As Object, ByVal ev As PrintPageEventArgs)
'DEFINI LA POSITION ET LA TAILLE DU GRAPHIQUE
Dim chartPosition As New Rectangle(-70, -50, 2500, 2300)
Chart_Requis.Printing.PrintPaint(ev.Graphics, chartPosition)
End Sub
Hope it will help someone in the same trouble than me today...

Related

moving many controls together to represent a Seating Chart in VB.NET

Greetings,
I want To create a graphic representation of a seating chart (could be in a wedding venue or in cars...). I used a splitted panel, in the splittedPanel1 i put the buttons to create the cars, and inside the splitted panel2 i want to put the graphic representation. Inside SplittedPanel2, I've created a panel and a pictureBox (to represent some fixed areas in the real world).
I've also created a class called SimpleCar. SimpleCar is composed of 5 TextBox (es) and a PictureBox all in a panel to represent a car: the textBoses represent the passengers names and the car label, and the pictureBox to put an image representing a car (or a table). I've also made a sub to Add dynamically a SimpleCar.
2 problems occur when i want to move this new panel (dynamically created), using MouseDown and MouseUp events:
- first pb: while moving the existing panel, the screen flashes and the movement is not smooth
- second pb: i can't move a panel dynamically created
Note that moving a PictureBox by this code is very smooth but moving a panel is not user friendly.
I expect moving a dynamically created a panel smoothly, or should I reconsider displaying the cars in another way than in a panel?
Knowing that the final purpose of the code is to export a picture of all the created tables in the venue. I also tested the code with a groupBox and the results aren't good.
The simpleCar class is described in the code below:
Class SimpleCar
Public carNameBox, passengerNameBox1, passengerNameBox2,
passengerNameBox3, passengerNameBox4 As TextBox
Public carPictureBox As PictureBox
Public carGroup As Panel
Public Sub New()
carGroup = New Panel
carNameBox = New TextBox With {.Text = "carNmBx",
.BackColor = Color.Yellow,
.Name = "carNmBx"}
passengerNameBox1 = New TextBox With {.Text = "txtPassNmBx1",
.BackColor = Color.BlanchedAlmond,
.Name = "TextBox1"}
passengerNameBox2 = New TextBox With {.Text = "txtPassNmBx2",
.BackColor = Color.AliceBlue,
.Name = "TextBox2"}
passengerNameBox3 = New TextBox With {.Text = "txtPassNmBx3",
.BackColor = Color.Azure,
.Name = "TextBox3"}
passengerNameBox4 = New TextBox With {.Text = "txtPassNmBx4",
.BackColor = Color.Cyan,
.Name = "TextBox4"}
carPictureBox = New PictureBox With {.Text = "picBx1",
.BackColor = Color.BlanchedAlmond,
.Name = "picBox1"}
Dim fdialog As New OpenFileDialog()
fdialog.FileName = String.Empty
fdialog.Multiselect = True
If fdialog.ShowDialog = DialogResult.OK Then
If fdialog.FileNames.Length = 2 Then
carPictureBox.Image = Image.FromFile(fdialog.FileNames(0))
ElseIf fdialog.FileNames.Length = 1 Then
carPictureBox.Image = Image.FromFile(fdialog.FileName)
End If
End If
carGroup.Controls.Add(carPictureBox)
carGroup.Controls.Add(carNameBox)
carGroup.Controls.Add(passengerNameBox1)
carGroup.Controls.Add(passengerNameBox2)
carGroup.Controls.Add(passengerNameBox3)
carGroup.Controls.Add(passengerNameBox4)
End Sub
End Class
To Add dynamically a SimpleCar in the code below:
Public Sub Add_car()
Dim carType As SimpleCar
carType = New SimpleCar
Dim carPs1 = carType.passengerNameBox1
Dim carPs2 = carType.passengerNameBox2
Dim carPs3 = carType.passengerNameBox3
Dim carPs4 = carType.passengerNameBox4
Dim carNm = carType.carNameBox
Dim carPic = carType.carPictureBox
Dim carGroupBox = carType.carGroup
SplitContainer1.Panel2.Controls.Add(carGroupBox)
End Sub
So the problem occurs when i use this code to move a panel (if you replace PictureBox by Panel, even GroupBox) (it worked fine when I wanted to move one control: PictureBox1 in this sample):
'Drag To move PictureBox1 along with mouse-------------------------------------------
Dim oldX As Short
Dim oldY As Short
Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles PictureBox1.MouseDown
Dim X As Single = e.X
Dim Y As Single = e.Y
PictureBox1.Cursor = Cursors.SizeAll
oldX = CShort(X)
oldY = CShort(Y)
End Sub
Private Sub PictureBox1_MouseUp(ByVal sender As Object, ByVal e As MouseEventArgs) Handles PictureBox1.MouseUp
Dim X As Single = e.X
Dim Y As Single = e.Y
PictureBox1.Cursor = Cursors.Default
End Sub
' to limit the movement within the app----------------------------------
Private Sub PictureBox1_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs) Handles PictureBox1.MouseMove
If e.Button = MouseButtons.Left Then
Dim ProposedLocation As New Point(PictureBox1.Left - (oldX - e.X), PictureBox1.Top - (oldY - e.Y))
PictureBox1.Left = CInt(IIf(ProposedLocation.X < 0, 0, IIf(ProposedLocation.X > SplitContainer1.Panel2.Width - PictureBox1.Width, SplitContainer1.Panel2.Width - PictureBox1.Width, ProposedLocation.X)))
PictureBox1.Top = CInt(IIf(ProposedLocation.Y < 0, 0, IIf(ProposedLocation.Y > SplitContainer1.Panel2.Height - PictureBox1.Height, SplitContainer1.Panel2.Height - PictureBox1.Height, ProposedLocation.Y)))
End If
End Sub

How to stop controls from flickering during MouseMove Event

I know this is a pretty popular question, but none of the solutions I have found have worked for me.
Background: I have a windows forms project in VS2015 that reads data from text files and plots the data as multiple series on a line chart. The Chart.MouseMove event finds the point nearest the mouse and draws a circle around it. The circle is drawn in the Chart_Paint event
Private Sub crtLogView(sender As Object,e As PaintEventArgs) Handles crtLogView.Paint
Dim whitePen as New Pne(Color.White,2)
e.Graphics.DrawEllipse(whitePen,cir) '//cir is a Public Rectangle
End Sub
When moving the mouse across the chart, random controls flicker off then back on which is very annoying. I have posted the MouseMove event code below.
Potential solutions I have tried:
Turning on the DoubleBuffered property of the form, which does nothing
Using the Me.Invalidate() and Me.Update() method, which does not move the circle
Using the Chart.Invalidate() and Chart.Update() method, which works, but is very slow
Adding the following code to my Form_Load routine, which appears to do nothing
Any help with this would be greatly appreciated
Me.SetStyle(ControlStyles.AllPaintingInWmPaint, True)
Me.SetStyle(ControlStyles.DoubleBuffer, True)
Me.SetStyle(ControlStyles.UserPaint, True)
MouseMove Event Code:
Private Sub crtLogView_MouseMove(sender As Object, e As MouseEventArgs) Handles crtLogView.MouseMove
'//Show data for closest point to cursor & draw circle around point
Dim hResult As HitTestResult = crtLogView.HitTest(e.X, e.Y)
Dim srsNam As String = ""
Dim mouseY As Single
Dim pntDist As Double = 0
Dim pntX As Single
Dim pntY As Single
Dim mouseX As Single
On Error GoTo ErrTrap
'//Get X-Axis Position as integer
mouseX = Int(hResult.ChartArea.AxisX.PixelPositionToValue(e.X))
'// Set time value
lblTime.Text = String.Format("{0:n2}", hResult.ChartArea.AxisX.PixelPositionToValue(e.X) / 160)
'//Get Y-Axis Position
mouseY = hResult.ChartArea.AxisY.PixelPositionToValue(e.Y)
'//Get distance from mouse to point on Series(0)
pntDist = Math.Abs(crtLogView.Series(0).Points(mouseX).YValues(0) - mouseY)
srsNam = crtLogView.Series(0).Name '//1st series name
'//Find closest series
For i As Integer = 1 To crtLogView.Series.Count - 1
If Math.Abs(crtLogView.Series(i).Points(mouseX).YValues(0) - mouseY) < pntDist Then
pntDist = Math.Abs(crtLogView.Series(i).Points(mouseX).YValues(0) - mouseY)
srsNam = crtLogView.Series(i).Name
End If
Next
'//Set Top/Left values for circle
pntY = crtLogView.ChartAreas(0).AxisY.ValueToPixelPosition(crtLogView.Series(srsNam).Points(mouseX).YValues(0)) - 4
pntX = crtLogView.ChartAreas(0).AxisX.ValueToPixelPosition(Val(mouseX)) - 4
'//Move circle to closest point
cir.Location = New Point(pntX, pntY)
'//Refresh the form to move the circle
'//This works, but takes 2+ seconds to take effect
'crtLogView.Invalidate()
'crtLogView.Update()
'//This does not work
'Me.Invalidate()
'Me.Update()
'//This works, but randomly makes other controls flash/flicker
Me.Refresh()
ErrTrap:
End Sub
In the comments, I offered to provide an example of using a Chart Annotation or a DataPoint Label as an alternative to custom painting a circle around the point under the mouse-cursor and have included that in the code below. However, I realized that a DataPoint Marker should provide the function the OP is seeking and is likely the proper solution. Therefore, that option is also included.
Annotations are chart level graphics where-as the DataPoint Label and DataPoint Marker are as the name implies tied to the individual DataPoints. Proper sizing of annotations can be involved as their size is specified as a percentage of the Chart Area dimensions. This example does not attempt to resize the annotation based on the current chart size.
The following code sample is for a WinForm. In VS, add a new Class to a WinForm project and replace the auto-generated code with this. The set this Form as the startup Form.
Imports System
Imports System.Drawing
Imports System.Windows.Forms
Imports Charting = System.Windows.Forms.DataVisualization.Charting
Public Class ChartDemo : Inherits Form
Const yMultiplyer As Double = 100.0
Private rnd As Random
Friend WithEvents chart As System.Windows.Forms.DataVisualization.Charting.Chart
Friend WithEvents rbAnnotation As System.Windows.Forms.RadioButton
Friend WithEvents rbDataLabel As System.Windows.Forms.RadioButton
Friend WithEvents rbMarker As System.Windows.Forms.RadioButton
Private lastPoint As Charting.DataPoint
Private ellispeAnnotation As Charting.EllipseAnnotation
Public Sub New()
InitializeComponent()
rnd = New Random(0) ' use same basis for each run
SetupChart()
End Sub
Private Sub InitializeComponent()
Me.chart = New System.Windows.Forms.DataVisualization.Charting.Chart()
Me.rbAnnotation = New System.Windows.Forms.RadioButton()
Me.rbDataLabel = New System.Windows.Forms.RadioButton()
Me.rbMarker = New System.Windows.Forms.RadioButton()
CType(Me.chart, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
Me.chart.Anchor = AnchorStyles.Top Or
AnchorStyles.Bottom Or
AnchorStyles.Left Or
AnchorStyles.Right
Me.chart.Location = New Point(4, 50)
Me.chart.Size = New Size(600, 500)
Me.rbAnnotation.AutoSize = True
Me.rbAnnotation.Location = New Point(50, 10)
Me.rbAnnotation.TabIndex = 1
Me.rbAnnotation.Text = "Use Annotation"
Me.rbAnnotation.UseVisualStyleBackColor = True
Me.rbDataLabel.AutoSize = True
Me.rbDataLabel.Location = New Point(200, 10)
Me.rbDataLabel.TabIndex = 2
Me.rbDataLabel.Text = "Use Data Label"
Me.rbDataLabel.UseVisualStyleBackColor = True
Me.rbMarker.AutoSize = True
Me.rbMarker.Location = New Point(400, 10)
Me.rbMarker.TabIndex = 3
Me.rbMarker.Text = "Use Data Marker"
Me.rbMarker.UseVisualStyleBackColor = True
Me.rbMarker.Checked = True
Me.AutoScaleDimensions = New SizeF(96.0!, 96.0!)
Me.AutoScaleMode = AutoScaleMode.Dpi
Me.ClientSize = New Size(610, 555)
Me.Controls.AddRange({Me.rbDataLabel, Me.rbAnnotation, Me.rbMarker, Me.chart})
Me.Text = "Charting Demo"
CType(Me.chart, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Private Sub SetupChart()
chart.ChartAreas.Clear()
chart.Legends.Clear()
chart.Series.Clear()
chart.Annotations.Clear()
Dim area1 As New Charting.ChartArea("Area1")
chart.ChartAreas.Add(area1)
Dim ser As Charting.Series = chart.Series.Add("Series1")
ser.ChartArea = area1.Name
ser.ChartType = Charting.SeriesChartType.Line
' define defaults for point DataLabels
ser.LabelBorderColor = Color.Red
ser.LabelBorderWidth = 1
ser.LabelBackColor = Color.WhiteSmoke
ser.LabelForeColor = Color.Black
' define defaults for point DataMarkers
ser.MarkerSize = 10
ser.MarkerBorderWidth = 3
ser.MarkerBorderColor = Color.Red
ser.MarkerColor = Color.Transparent
' points for demo chart
For x As Double = -5.0 To 5.0
ser.Points.AddXY(x, rnd.NextDouble * yMultiplyer)
Next
ellispeAnnotation = CreateEllipseAnnotation()
ellispeAnnotation.Visible = False
chart.Annotations.Add(ellispeAnnotation)
End Sub
Private Sub chart_MouseLeave(sender As Object, e As EventArgs) Handles chart.MouseLeave
ellispeAnnotation.Visible = False
ClearLastPointDataLabel()
ClearLastPointMarker()
End Sub
Private Function CreateEllipseAnnotation() As Charting.EllipseAnnotation
Dim ret As New Charting.EllipseAnnotation()
ret.ForeColor = Color.Black
ret.Font = New Font("Arial", 10)
ret.LineWidth = 2
ret.Height = 7.5 ' % ChartArea height
ret.Width = 15 ' % ChartArea width
ret.BackColor = Color.PaleGoldenrod
ret.LineDashStyle = Charting.ChartDashStyle.Solid
Return ret
End Function
Private Sub chart_MouseMove(sender As Object, e As MouseEventArgs) Handles chart.MouseMove
Dim htr As Charting.HitTestResult = chart.HitTest(e.X, e.Y)
If htr.ChartElementType = Charting.ChartElementType.DataPoint Then
Dim pt As Charting.DataPoint = DirectCast(htr.Object, Charting.DataPoint)
If pt IsNot lastPoint Then
SetDataPointLabel(pt)
SetDataPointAnnotation(pt)
SetDataPointMarker(pt)
lastPoint = pt
End If
End If
End Sub
Private Sub SetDataPointAnnotation(pt As Charting.DataPoint)
If rbAnnotation.Checked Then
ellispeAnnotation.AnchorDataPoint = pt
ellispeAnnotation.Text = String.Format("{0:N2}, {1:N2}", pt.XValue, pt.YValues(0))
ellispeAnnotation.Visible = True
End If
End Sub
Private Sub SetDataPointLabel(pt As Charting.DataPoint)
ClearLastPointDataLabel()
If rbDataLabel.Checked Then
pt.Label = "#VALX{N2}, #VALY{N2}" ' case sensative, use uppercase for #VALX, #VALY
pt.IsValueShownAsLabel = True
End If
End Sub
Private Sub ClearLastPointDataLabel()
If lastPoint IsNot Nothing Then
lastPoint.Label = String.Empty
lastPoint.IsValueShownAsLabel = False
End If
End Sub
Private Sub SetDataPointMarker(pt As Charting.DataPoint)
ClearLastPointMarker()
If rbMarker.Checked Then pt.MarkerStyle = Charting.MarkerStyle.Circle
End Sub
Private Sub ClearLastPointMarker()
If lastPoint IsNot Nothing Then
lastPoint.MarkerStyle = Charting.MarkerStyle.None
End If
End Sub
Private Sub rbAnnotation_CheckedChanged(sender As Object, e As EventArgs) Handles rbAnnotation.CheckedChanged
If Not rbAnnotation.Checked Then
ellispeAnnotation.Visible = False
End If
End Sub
Private Sub rbDataLabel_CheckedChanged(sender As Object, e As EventArgs) Handles rbDataLabel.CheckedChanged
ClearLastPointDataLabel()
End Sub
Private Sub rbMarker_CheckedChanged(sender As Object, e As EventArgs) Handles rbMarker.CheckedChanged
ClearLastPointMarker()
End Sub
End Class

Making labels in charts selectable/editable in VB

Just like in excel for a graph you can double click on a title, series name, or axis label and then you are able to type in that space. What do I need to do so I can do that for my charts? Clueless on where to start. Seems I may have to create a custom label?
Use the HitTest method of the chart.
Imports System.Windows.Forms.DataVisualization.Charting
Public Class Form1
Private Sub Chart1_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles Chart1.MouseDoubleClick
Dim h As HitTestResult = Chart1.HitTest(e.X, e.Y) 'Perform the HitTest with the mouse position that was clicked
If h.ChartElementType = ChartElementType.AxisTitle OrElse _
h.ChartElementType = ChartElementType.Axis Then 'Check the type of the element of the chart that was clicked
Dim s As String = InputBox("Please enter a new title!", "", h.Axis.Title) 'Prompt for a new title
If s <> "" Then h.Axis.Title = s 'Assign the new title
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For i = 1 To 20 'Put some data in the chart to make the axes visible
Chart1.Series(0).Points.AddXY(i, i ^ 2)
Next
End Sub
End Class
You basically use the mouse location for the HitTest method. The ChartElementType defines what element was clicked at the position. If it's the title of the axis or the axis itself it will prompt you with an InputBox for a new title and assigns this title.
The InputBox is pretty old and shouldn't really be used but I was lazy and it works :-)
Apparently, what I'm referring to lives in DataVisualization.Charting.TextAnnotation. Along with that one, are many more type of annotations.
A TextAnnotation allows: AnchorMoving, Moving, PathEditing, Resizing, Selecting, and TextEditing. All of which I'm looking for.
Simple setup:
Dim anno As New DataVisualization.Charting.TextAnnotation
anno.AllowTextEditing = true
anno.AllowSelecting = true
anno.AllowMoving = true
anno.AllowResizing = true
anno.x = 50
anno.y = 50
anno.text = "Your Text"
chart.annotations.add(xAxisAnno)

When creating a label a label inside a panel, the text is cut off VisualBasic

I wanted to be able to dynamically create a panel with a label on it, but the label isn't acting as I would expect it too, its cutting most of it off.
When I create a panel then create a label inside the panel, the text isn't displayed correctly. Anyone know how to fix it?
What is was supposed to do was to create a panel with text on it with the newpanel() sub
Dim timetable(5, 5) As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Width = (74 * 5) - 3
Me.Height = My.Computer.Screen.Bounds.Size.Height
Me.Top = My.Computer.Screen.Bounds.Top
Me.Left = My.Computer.Screen.Bounds.Right - Me.Width
GetTimetable()
End Sub
Private Sub newpanel(colour As Color, textT As String)
Dim Npan As New Panel
Npan.Top = 0
Npan.Left = 0
Npan.Width = Me.Width
Npan.Height = 64
Npan.BackColor = colour
Dim NpanT As New Label
NpanT.Parent = Npan
NpanT.Text = textT
Npan.Controls.Add(NpanT)
Me.Controls.Add(Npan)
End Sub
Private Sub GetTimetable()
'Dim path As String = My.Computer.FileSystem.SpecialDirectories.Desktop + "\Timetable"
newpanel(Color.Aqua, "this is a test! test testtesttest test test test")
End Sub
Looking at the MSDN page for the Label.AutoSize Property, it states as was mentioned above that the Labels AutoSize Property defaults to true in the designer, but it is false when created in code.
From above link:
When added to a form using the designer, the default value is true. When instantiated from code, the default value is false.
So you need to change your newpanel method to this:
Private Sub newpanel(colour As Color, textT As String)
Dim Npan As New Panel
Npan.Top = 0
Npan.Left = 0
Npan.Width = Me.Width
Npan.Height = 64
Npan.BackColor = colour
Dim NpanT As New Label
NpanT.Parent = Npan
NpanT.Text = textT
NpanT.AutoSize = True 'Enables Auto sizing
Npan.Controls.Add(NpanT)
Me.Controls.Add(Npan)
End Sub

Why do the WordWrap and AutoSize properties on a Text Box behave differently if the text boxes are added dynamically?

I am creating some textboxes dynamically in a custom control (actually is just a panel with a binding source that adds other sub controls at runtime.
In some of those I am setting WordWrap=True because I am expecting large text. But the textbox has only one line. Also I notice that I have to set the property AutoSize to False. When I add dynamically textboxes in a form everything is working fine (even without setting the AutoSize and the WordWrap.
Dim txt as new textbox
txt.Multiline = True
txt.AutoSize = False
txt.Size = New Size(100, 50)
txt.WordWrap = True
txt.Location = New Point(10, 10)
Me.Controls.Add(txt) 'Me is my custom Control
I checked the property WordWrap for the text box after I inserted them (with double click) and it is True.
Any ideas why I face this strange behaviour in my custom control?
Edit:
The problem is that I cannot make my text to wordwrap. So although I set MultiLine to true, AutoSize to false, WordWrap to True, the text is not changing lines. I don't want to add scrollbars.
You could adjust the .Height of the TextBox when its .Text changes:
Public Class Form1
Dim txt As TextBox
Sub maketb()
txt = New TextBox
txt.Multiline = True
txt.Size = New Size(100, 50)
txt.WordWrap = True
txt.Location = New Point(10, 10)
Me.Controls.Add(txt)
End Sub
Sub SetHeight(sender As Object, e As EventArgs)
Dim target = DirectCast(sender, TextBox)
Dim fn = target.Font
Dim gr = target.CreateGraphics()
Dim lrMarginSize = target.Margin.Left + target.Margin.Right
Dim tbMarginSize = target.Margin.Top + target.Margin.Bottom
Dim h = gr.MeasureString(target.Text, fn, target.Width - lrMarginSize).Height + tbMarginSize
target.Height = CInt(Math.Ceiling(h))
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
maketb()
AddHandler txt.TextChanged, AddressOf SetHeight
txt.Text = "dfgd dfd gg hgljhhkjlh jhkkj hkjh hghjg hgjhgz hfjsdhfytu hgjahg ht gretyt jgagury agha gty ajhg ajgx"
End Sub
End Class
Guys I have to apologize.
The error was in my xml (I had MultiLine instead of Multiline), so my textbox was never Multiline.
Thanks for your time, Sorry for spending it without meaning.