Call Base functions from Child in VB.net - vb.net-2010

How to call the base functions in vb.net?
Imports System.Data.Sql
Imports System.Data.SqlClient
Public Class Box
Public length As Double ' Length of a box
Public breadth As Double ' Breadth of a box
Public height As Double ' Height of a box
Public function setLength(ByVal len As Double)
length = len
End Sub
Public Sub setBreadth(ByVal bre As Double)
breadth = bre
End Sub
Public Sub setHeight(ByVal hei As Double)
height = hei
End Sub
Public Function getVolume() As Double
Return length * breadth * height
End Function
End Class
It says syntax error when I use MyBase to call the base functions
Public Class myChild : Inherits Box
'box 1 specification
MyBase.setLength(6.0)
MyBase.setBreadth(7.0)
MyBase.setHeight(5.0)
'box 2 specification
MyBase.setLength(12.0)
MyBase.setBreadth(13.0)
MyBase.setHeight(10.0)
'volume of box 1
volume = MyBase.getVolume()
Console.WriteLine("Volume of Box1 : {0}", volume)
'volume of box 2
volume = MyBase.getVolume()
End Class

You can't call MyBase from there as the object hasn't yet been constructed.
A better implementation would be:
Box.vb
Public Class Box
Private mLength As Double ' Length of a box
Private mBreadth As Double ' Breadth of a box
Private mHeight As Double ' Height of a box
Public Sub New(ByVal length As Double, ByVal breadth As Double, ByVal height As Double)
Me.mLength = length
Me.mBreadth = breadth
Me.mHeight = height
End Sub
Public Property Length As Double
Get
Return Me.mLength
End Get
Set(ByVal value As Double)
Me.mLength = value
End Set
End Property
Public Property Breadth As Double
Get
Return Me.mBreadth
End Get
Set(ByVal value As Double)
Me.mBreadth = value
End Set
End Property
Public Property Height As Double
Get
Return Me.mHeight
End Get
Set(ByVal value As Double)
Me.mHeight = value
End Set
End Property
Public Function getVolume() As Double
Return Length * Breadth * Height
End Function
End Class
Child.vb
Public Class Child : Inherits Box
Public Sub New(ByVal length As Double, ByVal breadth As Double, ByVal height As Double)
MyBase.New(length, breadth, height)
End Sub
End Class
Example
Sub Main()
Dim box1 As New Child(6.0, 7.0, 5.0)
Dim box2 As New Child(12.0, 13.0, 10.0)
Console.WriteLine("box1 volume is: {0}", box1.getVolume())
Console.WriteLine("box2 volume is: {0}", box2.getVolume())
End Sub

Related

Visual Basic BMI Calculator gives NaN result

I'm doing an IT course for college and one of the assignments requires you to create a BMI calculator in Visual Basic with the use of object orientated techniques. I'm not a very good programmer and thus I'm stuck on a problem I keep receiving. The code I'm using was given to me by someone who claimed it works, however when I run the program any results given are NaN.
Anyone have an idea as to what is wrong with the code in order to give me this result?
Here is the code I'm using:
Public Class Form1
Private Sub Button_Calculate_Click(sender As Object, e As EventArgs) Handles
Button_Calculate.Click
Dim height As Double = Double.Parse(TextBox_Height.Text)
Dim weight As Double = Double.Parse(TextBox_Weight.Text)
bmi.SetWeight(weight)
bmi.SetHeight(height)
TextBox_BMI.Text = Format(bmi.GetBMI(), "0.00")
End Sub
Private bmi As New BMI
End Class
In a separate class:
Public Class BMI
Public Function GetBMI()
Return (weight / (height ^ 2))
End Function
Public Function GetWeight()
Return weight
End Function
Public Function GetHeight()
Return height
End Function
Public Function SetWeight(_weight As Double)
Return weight = _weight
End Function
Public Function SetHeight(_height As Double)
Return height = _height
End Function
Private weight As Double
Private height As Double
End Class
There are a few problems with your (meaning kushlord420) solution.
Visual Basic code in case insensitive so bmi is the same as BMI
You never use the Form level variable bmi so delete.
You tried to write a custom constructor but in vb.net it is Sub New
You are converting the values in the weight and height text boxes to Double but your properties are type Single. Actually this should
be Single.TryParse but that is for another day.
Functions in vb.net must have a data type for the return value. This is provided in the first line of the function. Since you are
using Format on the return value I made the value a String and
converted the return value.
Fixed the constructor parameters to avoid ambiguity.
Sub Button_Calculate_Click(sender As Object, e As EventArgs) Handles Button_Calculate.Click
Dim bmi As New BMI(CSng(TextBox_Weight.Text), CSng(TextBox_Height.Text))
TextBox_BMI.Text = Format(bmi.GetBMI(), "0.00")
End Sub
Public Class BMI
Public Function GetBMI() As String
Return (Weight / (Height ^ 2)).ToString
End Function
Public Property Weight As Single
Public Property Height As Single
Public Sub New(wght As Single, hght As Single)
Weight = wght
Height = hght
End Sub
End Class
You really need something more like this:
Public Class BMI
Public Function GetBMI() As Double
Return (weight / (height ^ 2))
End Function
Public Property Weight As Double
Public Property Height As Double
Public Sub New(weight As Double, height As Double)
Me.Weight = weight
Me.Height = height
End Sub
End Class
Public Class Form1
Private Sub Button_Calculate_Click(sender As Object, e As EventArgs) Handles Button_Calculate.Click
Dim bmi As New BMI(CDbl(TextBox_Weight.Text), CDbl(TextBox_Height.Text))
TextBox_BMI.Text = Format(bmi.GetBMI(), "0.00")
End Sub
End Class
Or better yet, this:
Public Class BMI
Public Property Weight As Double
Public Property Height As Double
Public ReadOnly Property BMI As Double
Get
Return (Weight / (Height ^ 2))
End Get
End Property
Public Sub New()
End Sub
Public Sub New(weight As Double, height As Double)
Me.Weight = weight
Me.Height = height
End Sub
End Class
With the help of a friend, figured out my problem.
If anyone is curious, here is the code that made it work:
Public Class Form1
Sub Button_Calculate_Click(sender As Object, e As EventArgs) Handles
Button_Calculate.Click
Dim bmi As New BMI With {.Weight = CDbl(TextBox_Weight.Text), .Height =
CDbl(TextBox_Height.Text)}
TextBox_BMI.Text = Format(bmi.GetBMI(), "0.00")
End Sub
Private bmi As New BMI
End Class
And:
Public Class BMI
Public Function GetBMI()
Return (weight / (height ^ 2))
End Function
Property Weight As Single
Property Height As Single
Public Sub BMI(weight As Single, height As Single)
Me.Weight = weight
Me.Height = height
End Sub
End Class

VB.NET add databinding to textbox control

How do you create a databinding into a textbox that is created at runtime?
Code that created my textbox control
Private Function ADD_TEXTBOX_CONTROL(ByVal ParentControl As Control,
ByVal Name As String,
ByVal Text As String,
ByVal Width As Integer,
ByVal Pos_X As Integer,
ByVal Pos_Y As Integer,
ByVal oNewControlTooltip As String) As TextBox
Dim oTB As New TextBox
oTB.Name = Name
oTB.Text = Text
oTB.Width = Width
oTB.Location = New Drawing.Point(Pos_X, Pos_Y)
ParentControl.Controls.Add(oTB)
Return oTB
End Function
Lets say i would want to bind this textbox with a class property created in the namespace. So that if my textbox value changes, the Body_Cilinder.Height is adjusted as well.
Namespace BODY_NAMESPACE
' Class that defines all the Cilinders properties for easy access.
Class Body_Cilinder
' Counter to determinate the cilinder quantity required.
Public Shared Count As Integer = 0
' Property decalration fir cilinder properties
Private _Index As Integer
Private _Elevation As Double
Private _Height As Double
' Cilinder Index number As Integer for finding the position.
Public Property Index() As Integer
Get
Index = _Index
End Get
Set(ByVal value As Integer)
_Index = value
End Set
End Property
' Cilinder Elevation to define the cilinder elevation from the T.L.
Public Property Elevation() As Double
Get
Elevation = _Elevation
End Get
Set(value As Double)
_Elevation = value
End Set
End Property
' Cilinder Height to define the cilinder height.
Public Property Height() As Double
Get
Height = _Height
End Get
Set(value As Double)
_Height = value
End Set
End Property
' Add Cilinder count every-time a new "Body Cilinder" instance Is created
Public Sub New()
Count = Count + 1
End Sub
End Class
End Namespace
What do I need to add?
I found this example but I don't quite get how it functions
textBox1.DataBindings.Add _
(New Binding("Text", ds, "customers.custName"))
Link to source

Create VBA class in VB.net

Is it possible (using COM and regasm.exe) to have a vba function call a vb.net function - which creates the class in vb.net and then passes the class back to vba, where it is recognised as a vba class?
In VBA, I can work with classes by using Insert>Class Module. I have set up a function that creates a class.
Private length As Double
Private height As Double
Public Sub init(ByRef hgt As Double)
height = hgt
length = dbl_height()
End Sub
Public Function dbl_height()
dbl_height = height * 2
End Function
I can initialize it accordingly using this function:
Public Function CreateClassFunction(foo As Integer)
Dim my_rect As Rectangle
Set my_rect = New Rectangle
my_rect.init (foo)
Set CreateClassFunction = my_rect
End Function
I can also do the same thing in vb.net with virtually identical code.
Public Class Rectangle
Private length As Double
Private height As Double
Public Sub init(ByRef hgt As Double)
height = hgt
length = dbl_height()
End Sub
Public Function dbl_height()
dbl_height = height * 2
End Function
End Class
where this vb.net function creates the class:
Public Function CreateClassFunction(foo As Integer) As Rectangle
Dim my_rect As Rectangle
my_rect = New Rectangle
my_rect.init(foo)
CreateClassFunction = my_rect
End Function
I can pull in a Variant/Object/Rectangle into vba using:
Function MyCreateClass(a As Double)
Dim classLib As New MyAnalytics.Class1
Set MyCreateClass = classLib.CreateClassFunction(a)
End Function
However this object does not have the height or length variables. (It says "no variables" on the watch window)
Edit:
Amended code as per Mat's Mug answer:
Public Class Rectangle
Private plength As Double
Private pheight As Double
Public Property length() As Double
Get
Return plength
End Get
Set(ByVal value As Double)
plength = value
End Set
End Property
Public Property height() As Double
Get
Return pheight
End Get
Set(ByVal value As Double)
pheight = value
End Set
End Property
Public Sub init(ByRef hgt As Double)
height = hgt
length = dbl_height()
End Sub
Public Function dbl_height()
dbl_height = height * 2
End Function
End Class
and testing in VBA:
Function MyCreateClass(a As Double)
Dim classLib As New MyAnalytics.Class1
Set MyCreateClass = classLib.CreateClassFunction(a)
Debug.Print MyCreateClass.Height()
Debug.Print MyCreateClass.length()
MyCreateClass.Height = 30
MyCreateClass.length = 20
Debug.Print MyCreateClass.Height()
Debug.Print MyCreateClass.length()
MyCreateClass.init (100)
Debug.Print MyCreateClass.Height()
Debug.Print MyCreateClass.length()
End Function
It won't be recognized as a VBA class - it's not a VBA class, but a COM object.
Your Rectangle class has private fields. Private fields are, well, Private. This is, roughly, what VBA sees:
Public Class Rectangle
Sub init(ByRef hgt As Double)
Function dbl_height()
End Class
Where are the fields?
Private length As Double
Private height As Double
You haven't exposed them - as far as VBA goes, they don't exist.
Now, you could make them Public - but then you would be breaking encapsulation by exposing fields; don't do that!
Expose property getters instead, and setters if you want VBA code to be able to change the Length and Height properties of a Rectangle instance.

Create triggers related to variables

I have a class that looks like this:
Public Class LumberPiece
Public boardLength As Double
Public currentLeftEndPosition As Double
Public currentRightEndPosition As Double
Public Sub New(ByVal bl As Double, ByVal clp As Double)
boardLength = clsDimension.ConvertInchesToMillimeters(bl)
currentLeftEndPosition = clsDimension.ConvertInchesToMillimeters(clp)
currentRightEndPosition = clsDimension.ConvertInchesToMillimeters(clp + bl)
End Sub
End Class
I want to somehow have a trigger that calculates the currentRightEndPosition everytime that the currentLeftEndPosition is changed (rightEnd always equals leftend+ boardLength).
how can I do this?
You can do this using properties. By making the fields properties, you can control what happens when the property values are read and when they are set. For instance:
Public Class LumberPiece
Public Property BoardLength As Double
Public Property CurrentLeftEndPosition As Double
Get
Return _currentLeftEndPosition
End Get
Set(value As Double)
_currentLeftEndPosition = value
CurrentRightEndPosition = clsDimension.ConvertInchesToMillimeters(_currentLeftEndPosition + BoardLength)
End Set
End Property
Private _currentLeftEndPosition As Double
Public Property CurrentRightEndPosition As Double
Public Sub New(ByVal bl As Double, ByVal clp As Double)
BoardLength = clsDimension.ConvertInchesToMillimeters(bl)
CurrentLeftEndPosition = clsDimension.ConvertInchesToMillimeters(clp)
End Sub
End Class
Alternatively, you could choose to calculate the field every time it is accessed:
Public Class LumberPiece
Public Property BoardLength As Double
Public Property CurrentLeftEndPosition As Double
Public ReadOnly Property CurrentRightEndPosition As Double
Get
Return clsDimension.ConvertInchesToMillimeters(CurrentLeftEndPosition + BoardLength)
End Get
End Property
Public Sub New(ByVal bl As Double, ByVal clp As Double)
BoardLength = clsDimension.ConvertInchesToMillimeters(bl)
CurrentLeftEndPosition = clsDimension.ConvertInchesToMillimeters(clp)
End Sub
End Class

Font serialization in vb.net

as the title says , I need to serialize my font.
I have tried the following approach unfortunately to no avail.
This is what I have and what happens;
I have a drawing application and certain variables and properties need to be serialized.
(So , Xml.Serialization has been used.)
Now this has already been done in a huge portion and I've created some other attributes which needed to be serialized and it works.
There is one base class and classes such as drawablestar, drawableeclipse ,etc. all inherit from this class. As does my drawabletextboxclass.
The base class is Serializable as can be seen in the sample below.
It looks like this...
Imports System.Xml.Serialization
<Serializable()> _
Public MustInherit Class Drawable
' Drawing characteristics.
'Font characteristics
<XmlIgnore()> Public FontFamily As String
<XmlIgnore()> Public FontSize As Integer
<XmlIgnore()> Public FontType As Integer
<XmlIgnore()> Public ForeColor As Color
<XmlIgnore()> Public FillColor As Color
<XmlAttributeAttribute()> Public LineWidth As Integer = 0
<XmlAttributeAttribute()> Public X1 As Integer
<XmlAttributeAttribute()> Public Y1 As Integer
<XmlAttributeAttribute()> Public X2 As Integer
<XmlAttributeAttribute()> Public Y2 As Integer
' attributes for size textbox
<XmlAttributeAttribute()> Public widthLabel As Integer
<XmlAttributeAttribute()> Public heightLabel As Integer
'<XmlTextAttribute()> Public FontFamily As String
'<XmlAttributeAttribute()> Public FontSize As Integer
'this should actually not be here..
<XmlAttributeAttribute()> Public s_InsertLabel As String
' Indicates whether we should draw as selected.
<XmlIgnore()> Public IsSelected As Boolean = False
' Constructors.
Public Sub New()
ForeColor = Color.Black
FillColor = Color.White
'FontFamily = "Impact"
'FontSize = 12
End Sub
Friend WriteOnly Property _Label() As String
Set(ByVal Value As String)
s_InsertLabel = Value
End Set
End Property
Public Sub New(ByVal fore_color As Color, ByVal fill_color As Color, Optional ByVal line_width As Integer = 0)
LineWidth = line_width
ForeColor = fore_color
FillColor = fill_color
' FontFamily = Font_Family
' FontSize = Font_Size
End Sub
' Property procedures to serialize and
' deserialize ForeColor and FillColor.
<XmlAttributeAttribute("ForeColor")> _
Public Property ForeColorArgb() As Integer
Get
Return ForeColor.ToArgb()
End Get
Set(ByVal Value As Integer)
ForeColor = Color.FromArgb(Value)
End Set
End Property
<XmlAttributeAttribute("BackColor")> _
Public Property FillColorArgb() As Integer
Get
Return FillColor.ToArgb()
End Get
Set(ByVal Value As Integer)
FillColor = Color.FromArgb(Value)
End Set
End Property
'Property procedures to serialize and
'deserialize Font
<XmlAttributeAttribute("InsertLabel")> _
Public Property InsertLabel_() As String
Get
Return s_InsertLabel
End Get
Set(ByVal value As String)
s_InsertLabel = value
End Set
End Property
<XmlAttributeAttribute("FontSize")> _
Public Property FontSizeGet() As Integer
Get
Return FontSize
End Get
Set(ByVal value As Integer)
FontSize = value
End Set
End Property
<XmlAttributeAttribute("FontFamily")> _
Public Property FontFamilyGet() As String
Get
Return FontFamily
End Get
Set(ByVal value As String)
FontFamily = value
End Set
End Property
<XmlAttributeAttribute("FontType")> _
Public Property FontType_() As Integer
Get
Return FontType
End Get
Set(ByVal value As Integer)
FontType = value
End Set
End Property
#Region "Methods to override"
Public MustOverride Sub Draw(ByVal gr As Graphics)
' Return the object's bounding rectangle.
Public MustOverride Function GetBounds() As Rectangle
...... ........
.....
End Class
My textbox class which looks like this , is the one that needs to save it's font.
Imports System.Math
Imports System.Xml.Serialization
Imports System.Windows.Forms
<Serializable()> _
Public Class DrawableTextBox
Inherits Drawable
Private i_StringLength As Integer
Private i_StringWidth As Integer
Private drawFont As Font = New Font(FontFamily, 12, FontStyle.Regular)
Private brsTextColor As Brush = Brushes.Black
Private s_insertLabelTextbox As String = "label"
' Constructors.
Public Sub New()
End Sub
Public Sub New(ByVal objCanvas As PictureBox, ByVal fore_color As Color, ByVal fill_color As Color, Optional ByVal line_width As Integer = 0, Optional ByVal new_x1 As Integer = 0, Optional ByVal new_y1 As Integer = 0, Optional ByVal new_x2 As Integer = 1, Optional ByVal new_y2 As Integer = 1)
MyBase.New(fore_color, fill_color, line_width)
Dim objGraphics As Graphics = objCanvas.CreateGraphics()
X1 = new_x1
Y1 = new_y1
'Only rectangles ,circles and stars can resize for now b_Movement
b_Movement = True
Dim frm As New frmTextbox
frm.MyFont = drawFont
frm.ShowDialog()
If frm.DialogResult = DialogResult.OK Then
FontFamily = frm.MyFont.FontFamily.Name
FontSize = frm.MyFont.Size
FontType = frm.MyFont.Style
'drawFont = frm.MyFont
drawFont = New Font(FontFamily, FontSize)
drawFont = FontAttributes()
brsTextColor = New SolidBrush(frm.txtLabel.ForeColor)
s_InsertLabel = frm.txtLabel.Text
i_StringLength = s_InsertLabel.Length
'gefixtf
Dim objSizeF As SizeF = objGraphics.MeasureString(s_InsertLabel, drawFont, New PointF(X2 - X1, Y2 - Y1), New StringFormat(StringFormatFlags.NoClip))
Dim objPoint As Point = objCanvas.PointToClient(New Point(X1 + objSizeF.Width, Y1 + objSizeF.Height))
widthLabel = objSizeF.Width
heightLabel = objSizeF.Height
X2 = X1 + widthLabel
Y2 = Y1 + heightLabel
Else
Throw New ApplicationException()
End If
End Sub
' Draw the object on this Graphics surface.
Public Overrides Sub Draw(ByVal gr As System.Drawing.Graphics)
' Make a Rectangle representing this rectangle.
Dim rectString As Rectangle
rectString = New Rectangle(X1, Y1, widthLabel, heightLabel)
rectString = GetBounds()
' See if we're selected.
If IsSelected Then
gr.DrawString(s_InsertLabel, drawFont, brsTextColor, X1, Y1)
'gr.DrawRectangle(Pens.Black, rect) ' Pens.Transparent
gr.DrawRectangle(Pens.Black, rectString)
' Draw grab handles.
DrawGrabHandle(gr, X1, Y1)
DrawGrabHandle(gr, X1, Y2)
DrawGrabHandle(gr, X2, Y2)
DrawGrabHandle(gr, X2, Y1)
Else
gr.DrawString(s_InsertLabel, drawFont, brsTextColor, X1, Y1)
'gr.DrawRectangle(Pens.Black, rect) ' Pens.Transparent
gr.DrawRectangle(Pens.Black, rectString)
End If
End Sub
'get fontattributes
Public Function FontAttributes() As Font
Return New Font(FontFamily, 12, FontStyle.Regular)
End Function
' Return the object's bounding rectangle.
Public Overrides Function GetBounds() As System.Drawing.Rectangle
Return New Rectangle( _
Min(X1, X1), _
Min(Y1, Y1), _
Abs(widthLabel), _
Abs(heightLabel))
End Function
' Return True if this point is on the object.
Public Overrides Function IsAt(ByVal x As Integer, ByVal y As Integer) As Boolean
Return (x >= Min(X1, X2)) AndAlso _
(x <= Max(X1, X2)) AndAlso _
(y >= Min(Y1, Y2)) AndAlso _
(y <= Max(Y1, Y2))
End Function
' Move the second point.
Public Overrides Sub NewPoint(ByVal x As Integer, ByVal y As Integer)
X2 = x
Y2 = y
End Sub
' Return True if the object is empty (e.g. a zero-length line).
Public Overrides Function IsEmpty() As Boolean
Return (X1 = X2) AndAlso (Y1 = Y2)
End Function
End Class
The coordinates ( X1 ,X2,Y1, Y2 ) are needed to draw a circle , rectangle etc. ( in the other classes ).This all works.
If I load my saved file it shows me the correct location and correct size of drawn objects. If I open my xml file I can see all values are correctly saved ( including my FontFamily ).
Also the color which can be adjusted is saved and then properly displayed when I load a previously saved drawing.
Of course because the coordinates work, if I insert a textField ,the location where it is being displayed is correct.
However here comes the problem , my fontSize and fontfamily don't work.
As you can see I created them in the base class, However this does not
work. Is my approach completely off? What can I do ?
Before saving
img14.imageshack.us/i/beforeos.jpg/
After loading the Font jumps back to Sans serif and size 12.
I could really use some help here..
Edit: I've been using the sample from this website
http://www.vb-helper.com/howto_net_drawing_framework.html
UPDATE:
The problem with creating a font property is that the xml serializer just won't take it.
#OregonGhost I'm certain that's what you mean as well , I'm just not really following your solution( thought i did , forgive me ).
So I figured hey why not create some sort of font class that would inherit from my base class since this one will be serialized( a bit crazy I know.. creating a font class for a font class) . So that I could create my " own " font objects instead of using the standard font class( since this one doesn't work with xml serializer). But decided not to do it.
#OregonGhost Now I saw something in indeed c# and I'm assuming you mean indeed something like this
public Font FontObject
{
get
{
return (Font) settings["font"];
}
set
{
settings["font"] = value;
}
}
In which settings is a hashtable.
Are you suggesting something like this ?