Rediming an array causes an exception on End Sub

  • Thread starter Thread starter Ashish
  • Start date Start date
A

Ashish

Hi, please take a look at the following code. (I've ommitted the Windows
generated code)
--------------------------------
Imports System.Drawing.Drawing2D
Public Class Form1
Inherits System.Windows.Forms.Form
Dim points() As Point = {}
Dim pen As New Pen(Color.FromArgb(255, 0, 0, 255))
Protected Overrides Sub OnPaint(ByVal e As
System.Windows.Forms.PaintEventArgs)
If points.Length > 0 Then
e.Graphics.DrawCurve(pen, points)
End If
End Sub

Protected Overrides Sub OnMouseDown(ByVal e As
System.Windows.Forms.MouseEventArgs)
If e.Button = MouseButtons.Right Then
' clear points
ReDim points(-1)
Me.Refresh()
End If
If e.Button = MouseButtons.Left Then
ReDim Preserve points(points.Length)
Dim p As New Point(e.X, e.Y)
points(points.Length - 1) = p
Me.Refresh()
End If
End Sub
End Class
---------------------
On mousedown, the array 'points' gets lengthened by 1 and the curve is
redrawn. But, on exiting from the sub, it gives an InvalidArgumentException.
But if I dont Redim the array, the code runs fine.

Whats going on???

Thanks in advance.
 
It's probably because the DrawCurve method takes a Point array that requires
at least 4 points. You are starting with an empty array and only adding one
point with each mouse click. You then try to draw the curve if the array
contains at least one point. You should change the OnPaint code to the
following:

If points.length > 3 Then
e.Graphics.DrawCurve(pen, points)
End If
 
I dont think thats the problem. I had the Me.Refresh() and DrawCurve()
methods commented. So, it never drew a graph. But still gave the exception.
On commenting the Redim statement, I no longer got any exceptions.

-Ashish
 
Scott said:
It's probably because the DrawCurve method takes a Point array that requires
at least 4 points. You are starting with an empty array and only adding one
point with each mouse click. You then try to draw the curve if the array
contains at least one point. You should change the OnPaint code to the
following:

By the way, the DrawCurve method can take less than 4 points and works
perfectly well.

-Ashish
 
Hi Ashish,

Indeed it does work with less that four points, but it really needs at least
two (what does a spline with only one point look like?). I have taken your
code and changed the "If points.Length > 0 Then" line to read "If
points.Length > 1 Then" and it works without error.

Please give that a try and let me know if it works for you.

HTH,
Derrick
 
Works like a charm! Thanks Derrick
-Ashish


Derrick said:
Hi Ashish,

Indeed it does work with less that four points, but it really needs at least
two (what does a spline with only one point look like?). I have taken your
code and changed the "If points.Length > 0 Then" line to read "If
points.Length > 1 Then" and it works without error.

Please give that a try and let me know if it works for you.

HTH,
Derrick
 
Back
Top