How to assign a Class to an array in vb.net - arrays

I have a little problem I can't figure out. I want to assign a class to an array but vb.net says, on line 7, that I cannot use the keyword 'New' to someArray(2).
How can I simply achieve what I try to do?
Public Class Form1
Public Class someClass
Public someName As String
Public someNumber As Integer
End Class
Public someRecord As New someClass
Public someArray(2) As New someClass
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
someRecord.someName = "A text"
someRecord.someNumber = 10
someArray(0).someName = "A text"
someArray(0).someNumber = 10
End Sub
End Class

The way it works is that you tell it what the array is made of, and then you need to assign an instance of the class to the array element:
Public Class Form1
Public Class SomeClass
Public someName As String
Public someNumber As Integer
End Class
Public someArray(2) As SomeClass
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim someRecord As New SomeClass
someRecord.someName = "A text"
someRecord.someNumber = 10
someArray(0) = someRecord
' Fill the rest of the array with default instances...
For i = 1 To someArray.Length - 1
someArray(i) = New SomeClass()
Next
End Sub
End Class

Related

How is an array with a length declared within a class? [Visual Basic]

I want to declare an array with a set length as a Public Property within a class, and fill the array with zeroes so that squares(0) = squares(5) = squares(42) = 0, etc.
What I tried:
Public Class Board
Public Property squares(width*height) As Integer
End Class
What I expected:
squares = {0,0,0,0,0,0,0,0}
What actually happened:
Error BC36759: Auto-implemented properties cannot have parameters
Public Class Board
Public Property squares As Integer()
Sub New(ArraySize As Integer)
ReDim squares(ArraySize)
End Sub
End Class
When you create the class, you create it like:
MyBoard = New Board(64)
Here's a variation, if your size is hard-coded:
Public Class Board
Private width As Integer = 5
Private height As Integer = 10
Private _squares(width * height) As Integer
Public ReadOnly Property squares As Integer()
Get
Return _squares
End Get
End Property
End Class
Or
Public Class Board
Private _board() As Integer = New Integer() {}
Public ReadOnly Property Squares() As Integer()
Get
Return Me._board
End Get
End Property
Public Sub New(width As Integer, height As Integer)
Array.Resize(Me._board, width * height)
End Sub
End Class
A simpler variation, maintaining the auto-property and no private field:
Public Class Board
Private Const width As Integer = 5
Private Const height As Integer = 10
Public Property squares() As Integer() = New Integer(width * height) {}
End Class

Add commands for PropertyGrid

I feel that it's something elementary but I can't find out how to add to class commands for PropertyGrid.
There is a sample class (the real classes are much more complex, but I need only the simplest example to implement the required functionality)
Public Class SampleClass
Public Const DefValue = 1
Public Property Value1 As Integer = DefValue
Public Property Value2 As Integer = DefValue
Public Sub Reset()
Value1 = DefValue
Value2 = DefValue
End Sub
End Class
Used In the sample form:
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Partial Class Form1
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()>
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()>
Private Sub InitializeComponent()
Me.PropertyGrid1 = New System.Windows.Forms.PropertyGrid()
Me.SuspendLayout()
'
'PropertyGrid1
'
Me.PropertyGrid1.Location = New System.Drawing.Point(242, 98)
Me.PropertyGrid1.Name = "PropertyGrid1"
Me.PropertyGrid1.Size = New System.Drawing.Size(294, 250)
Me.PropertyGrid1.TabIndex = 0
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(7.0!, 15.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(800, 450)
Me.Controls.Add(Me.PropertyGrid1)
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)
End Sub
Friend WithEvents PropertyGrid1 As PropertyGrid
End Class
An instance is attached to PropertyGrid by the next piece of code:
Public Class Form1
Private Sample As New SampleClass
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
PropertyGrid1.SelectedObject = Sample
End Sub
End Class
The goal is to have a link that resets the contents of the instance at bottom of PropertyGrid like in the picture below, I presume that some attribute for a class is required but can't find what attribute.
Thanks for any advice.

Can't figure out making an Array based off of a Class

What I'm trying to do is create an array from a Class that holds a list of information.
What I've tried so far is this - First, create the Class:
Public Class PowerArray
Public Name As String
Public Action As String
Public Cost As Integer
Public Pool1 As String
Public Pool2 As String
Public Range As String
Public Duration As String
Public Tags As ArrayList = New ArrayList
Public Desc As String
End Class
Then, define a new object that uses PowerArray as type, contained in a Public Class so it can be called in any sub:
Public Class GVar
Public Shared CharPowers(100) As PowerArray
Public Shared PCount As Integer = 0
End Class
But when I try to write to that object, it keeps throwing a Null Reference Exception.
Example:
Trying to write an entry to CharPowers(GVar.Pcount) (where PCount is currently 0, and "txt.PowerName.Text" is any string):
GVar.CharPowers(GVar.PCount).Name = txtPowerName.Text
...throws the exception. This happens no matter which value I try to write to.
I haven't had any major hangups going this route when defining a new object inside a sub using that type (not as an array, but just a simple object), so I'm guessing it's the object being an array that's throwing a fit. I just can't figure out how or why. It clearly exists, it's defined on startup.
Your array in GVar is an array of elements typed as PowerArray with a value of Nothing. You must create an instance of PowerArray and assign it to an element is the array before you can set a field of a PowerArray object.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim PA As New PowerArray
GVar.CharPowers(GVar.PCount) = PA
GVar.CharPowers(GVar.PCount).Name = TextBox1.Text
MessageBox.Show(GVar.CharPowers(GVar.PCount).Name)
End Sub
Are you planning on incrementing PCount? You would not need to keep track of where you are in the array if you used List(Of PowerArray).
EDIT
Public Class PowerArray
Public Property Name As String
Public Property Action As String
Public Property Cost As Integer
Public Property Pool1 As String
Public Property Pool2 As String
Public Property Range As String
Public Property Duration As String
Public Property Tags As New List(Of Object)
Public Property Desc As String
End Class
Public Class GVar
Public Shared Property CharPowers As New List(Of PowerArray)
End Class
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim PA As New PowerArray
PA.Name = TextBox1.Text
GVar.CharPowers.Add(PA)
For Each item As PowerArray In GVar.CharPowers
MessageBox.Show(item.Name)
Next
End Sub
Seems I tripped over an answer. In particular:
Public Class GVar
Public Shared CharPowers(100) As PowerArray
Public Shared PCount As Integer = 0
Shared Sub New()
For i = 0 To CharPowers.GetUpperBound(0)
CharPowers(i) = New PowerArray
Next
End Sub
End Class

WPF avoid adding a duplicate row

I'm using vb.net framework 4.5 and WPF project.
I have a button, the function adds a certain product info to a datagrid. In my vb code file I set a product class
Public Class MyProduct
Public Property ItemNumber As String
Public Property ItemDescription As String
Public Property ItemUnitPrice As Double
Public Property ItemQty As Integer
End Class
The button touchdown event
Private Sub Button_TouchDown(sender As Object, e As TouchEventArgs)
Dim dmb As New MyProduct
dmb.ItemNumber = "abc001"
dmb.ItemDescription = "bla bla bla"
dmb.ItemQty = 1
dmb.ItemUnitPrice = 123.45
MyDataGrid.Items.Add(dmb)
End Sub
Currently, if I tap multiple times of this button, the data grid will add multiple duplicated rows for same product. My goal is when multiple same product add to datagrid, only one row shows and each additional tap/click action on the same button will only increase the ItemQty number.
How can I do that? Thanks!
First, you need to prevent inserting twice :
Private Sub buttonAdd_Click(sender As Object, e As RoutedEventArgs) Handles buttonAdd.Click
Dim dmb As New MyProduct
dmb.ItemNumber = New Random().Next(5).ToString()
dmb.ItemDescription = "bla bla bla"
dmb.ItemQty = 1
dmb.ItemUnitPrice = 123.45
Dim dmbSearched As MyProduct = Nothing
For Each dmbs As MyProduct In MyDataGrid.Items
If dmbs.ItemNumber = dmb.ItemNumber Then
dmbSearched = dmbs
Exit For
End If
Next
If dmbSearched Is Nothing Then
MyDataGrid.Items.Add(dmb)
Else
dmbSearched.ItemQty += 1
End If
End Sub
Second the MyProduct class must raise an event when the quantity is changed, otherwise there is no visible change :
Public Class MyProduct : Implements INotifyPropertyChanged
Private Property m_ItemQty As Integer
Public Property ItemQty As Integer
Get
Return m_ItemQty
End Get
Set(value As Integer)
m_ItemQty = value
FirePropertyChanged()
End Set
End Property
Public Sub FirePropertyChanged(<CallerMemberName> Optional propName As String = "")
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propName))
End Sub
Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged
Public Property ItemNumber As String
Public Property ItemDescription As String
Public Property ItemUnitPrice As Double
End Class
Regards

Input textbox data into array of objects

I am using the module to declare the public class patient across all forms of my program. What do I have to do in order to input data into the array from three text boxes. One for Names, Heights, and Weights. Thanks
Public Module Module1
Public PatientCount As Integer = 0
Public Class Patient
Public Property Name As String = String.Empty
Public Property Height As Decimal = 0
Public Property Weight As Decimal = 0
End Class
End Module
Dim patients As List(Of Patient) = New List(Of Patient)
For displaying patients in listbox
For Each p As Module1.Patient In Patients
lstPatients.Items.Add(p.Name)
Next
CURRENT CODE:
MODULE
Public Module Module1
Public PatientCount As Integer = 0
Public Patients As List(Of Patient) = New List(Of Patient)
Public Class Patient
Public Property Name As String
Public Property Height As Decimal
Public Property Weight As Decimal
Public Sub New(ByVal name As String, ByVal height As Decimal, ByVal weight As Decimal)
name = _Name
weight = _Weight
height = _Height
End Sub
End Class
End Module
FORM 2 (Entry of Data)
Public Class Form2
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMainMenu.Click
Me.Close()
End Sub
Private Sub btnEnterPatient_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnterPatient.Click
patients.Add(New Patient(txtName.Text, CDec(txtHeight.Text), CDec(txtWeight.Text)))
PatientCount = PatientCount + 1
Label1.Text = PatientCount
End Sub
End Class
FORM 3 (Listing of Data)
Public Class Form3
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For Each p As Patient In Patients
lstPatients.Items.Add("Name: " & p.Name)
lstPatients.Items.Add("Weight: " & p.Weight)
lstPatients.Items.Add("Height: " & p.Height)
lstPatients.Items.Add("___________")
Next
End Sub
End Class
To store the data of an x number of patients, you could have this code in a button-clicked event handler.
Private Sub ButtonOK_Click()Handles BtnOk.Click()
patients.Add(New Module1.Patient(txtName.Text, CDec(txtHeight.Text), CDec(txtWeight.text))
End Sub
And then add this to your Patient class:
Public Module Module1
Public Class Patient
Public Property Name As String = String.Empty
Public Property Height As Decimal = 0
Public Property Weight As Decimal = 0
Public Sub New(_name as String, _height as decimal, _weight as decimal)
Name = _name
Weight = _weight
Height = _height
End Sub
End Class
End Module
Dim patients As List(Of Patient) = New List(Of Patient)
With this, you will create a list of patients every time the btnOk is pressed, and you can easily access any patient and their data.
To put the data in a listbox:
Private Sub BTNLIST_Click()Handles BTNLIST.Click
For Each p As Patient in patients
lstbox.Items.Add("Name: " & p.Name)
lstbox.Items.Add("Weight: " & p.Weight)
lstbox.Items.Add("Height: " & p.Height)
lstbox.Items.Add("___________")
Next
End Sub
OPTIONAL
You could even create a PatientList Class to help you further (but remove the patients List). You could use the PatientList class to add helpful functions, such as finding a patient by name or height.:
Public Class PatientList
Public List(Of Patient) Patients = New List(Of Patient)
Public ReadOnly Property PatientCount() As Integer
Get
Return Patients.Count
End Get
End Property
Public Sub AddPatientToList(name as String, height as decimal, weight as decimal)
Patients.Add(New Patient(name, height, weight)
End Sub
End Class
Dim patients as PatientList
Then add this in your button_click Handler:
Private Sub ButtonOK_Click()Handles BtnOk.Click()
patients.AddPatientToList(New Module1.Patient(txtName.Text, CDec(txtHeight.Text), CDec(txtWeight.text))
End Sub
HTH
One option would be to have a New constructor that takes the 3 values for the properties.
Public Module Module1
Public PatientCount As Integer = 0
Public Class Patient
Public Property Name As String = String.Empty
Public Property Height As Decimal = 0
Public Property Weight As Decimal = 0
Public Sub New(_name As String, _height As Decimal, _weight As Decimal)
Name = _name
Height = _height
Weight = _weight
End Sub
End Class
End Module
Dim patients As List(Of Patient) = New List(Of Patient)
Assuming you've validated the input from the textboxes and converted them to variables(NewName, NewHeight, NewWeight), you would add a new patient something like this:
patients.Add(New Patient(NewName,NewHeight,NewWeight))
If you want to add a patient then you need to create an instance of one and set it properties with the textboxes of whatever form your using. Then add the new patient to the list of patients, so something like this.
Dim patient as new Patient()
patient.Name = txtName.Text()
patient.Height = txtHeight.Text()
patient.Weight = txtWeight.Text()
patients.Add(patient)

Resources