How can I print from an object? - vb.net

I am having a problem getting my program to print an array. I have created a class with code and I want to be able to use the class to print the array. I have submitted my code below. hopefully Y'all can help me out thanks.
Option Strict On
Imports System.IO
Imports FinalLIB
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim fsrFile As StreamReader = New StreamReader("Cars.csv")
Dim line, splitLine(1) As String
Dim bestCars(14) As Cars
Dim counter As Integer
Do Until fsrFile.EndOfStream
line = fsrFile.ReadLine
splitLine = Split(line, ",")
bestCars(counter) = New Cars(splitLine(0), (splitLine(1)), (splitLine(2)), (splitLine(3)))
counter += 1
Loop
Dim strCarMake, strCarModel, intyear, strColorc As Cars
Console.WriteLine(bestCars(3))
End Sub
This is the code from my library created.
Option Strict On
Public Class Cars
Private strCarMake As String
Private strCarModel As String
Private intYear As String
Private strColor As String
Public Sub New(ByVal bvstrCarMake As String, ByVal bvstrCarModel As String, ByVal bvintYear As String, ByVal bvstrColor As String)
prpCarMake = bvstrCarMake
prpYear = CInt(bvintYear)
prpCarModel = bvstrCarModel
prpColor = bvstrColor
End Sub
Public Property prpCarMake() As String
Get
Return strCarMake
End Get
Set(bvstrCarMake As String)
strCarMake = bvstrCarMake
End Set
End Property
Public Property prpCarModel() As String
Get
Return strCarModel
End Get
Set(bvstrCarModel As String)
strCarModel = bvstrCarModel
End Set
End Property
Public Property prpYear() As Integer
Get
Return CInt(intYear)
End Get
Set(bvintYear As Integer)
intYear = CType(bvintYear, String)
End Set
End Property
Public Property prpColor() As String
Get
Return strColor
End Get
Set(bvstrColor As String)
strColor = bvstrColor
End Set
End Property
Public ReadOnly Property prpIsOld() As Boolean
Get
If prpYear > 2010 Then
Return True
Else
Return False
End If
End Get
End Property
'Public ReadOnly Property prpSSN() As String
'Get
'Return strSSN
'End Get
'End Property
Public Function ReturnFullInfo() As String
Return "Make: " & prpCarMake & " Model: " & prpCarModel & "Year: " & prpYear & "Color: " & prpColor
End Function
End Class

Related

Search dgv column by Column("TagIndex = 5")

I'm trying to get data from a DGV grid onto specific tags, and so far it has been working great. But an update moved the tags positions in the DGV so Rows(x) does not equal the tags I'm moving data into anymore.
Is it possible to do a search like the one I'm doing in Cells("Val") but in the Rows("") instead?
Actually I want it to be something like this Rows("TagIndex = 5") etc.
A full line of code would then be:
HopperStatus = dgvDataFlt.Rows("TagIndex = 5").Cells("Val").Value
but is this possible.
Row 12 & 13 are switched when logging
dgvDataFLT = dgvDataFloating
If dgvDataFlt.Rows(0).Cells("TagIndex").Value = 12 Then
'DGVDataFlt.AutoResizeColumns()
'--------------------------------------Floating TAGS fra database------------------------------------------
ProdRecCnt = dgvDataFlt.Rows(10).Cells("Val").Value
ProdTotCnt = dgvDataFlt.Rows(9).Cells("Val").Value
FrontFree = dgvDataFlt.Rows(8).Cells("Val").Value
CurrAutoMode = dgvDataFlt.Rows(7).Cells("Val").Value
PalletStatus = dgvDataFlt.Rows(6).Cells("Val").Value
HopperStatus = dgvDataFlt.Rows(5).Cells("Val").Value
PowerStatus = dgvDataFlt.Rows(4).Cells("Val").Value
CurrRecNo = dgvDataFlt.Rows(3).Cells("Val").Value
NomCycTime = dgvDataFlt.Rows(2).Cells("Val").Value
AutoStart = dgvDataFlt.Rows(1).Cells("Val").Value
MachineNo = dgvDataFlt.Rows(0).Cells("Val").Value
LOGTimeStamp = dgvDataFlt.Rows(0).Cells("DateAndTime").Value 'for aktuelle lognings tidstempel
LOGDateStamp = Microsoft.VisualBasic.Left(LOGTimeStamp, 10)
LOGClockStamp = Microsoft.VisualBasic.Mid(LOGTimeStamp, 12, 5)
End If
I want the code to look/work something like this:
If dgvDataFlt.Rows(0).Cells("TagIndex").Value = 12 Then
'DGVDataFlt.AutoResizeColumns()
'--------------------------------------Floating TAGS fra database------------------------------------------
ProdRecCnt = dgvDataFlt.Rows("TagIndex = 10").Cells("Val").Value
ProdTotCnt = dgvDataFlt.Rows("TagIndex = 9").Cells("Val").Value
FrontFree = dgvDataFlt.Rows("TagIndex = 8").Cells("Val").Value
CurrAutoMode = dgvDataFlt.Rows("TagIndex = 7").Cells("Val").Value
PalletStatus = dgvDataFlt.Rows("TagIndex = 6").Cells("Val").Value
HopperStatus = dgvDataFlt.Rows("TagIndex = 5").Cells("Val").Value
PowerStatus = dgvDataFlt.Rows("TagIndex = 4").Cells("Val").Value
CurrRecNo = dgvDataFlt.Rows("TagIndex = 3").Cells("Val").Value
NomCycTime = dgvDataFlt.Rows("TagIndex = 2").Cells("Val").Value
AutoStart = dgvDataFlt.Rows("TagIndex = 1").Cells("Val").Value
MachineNo = dgvDataFlt.Rows("TagIndex = 0").Cells("Val").Value
LOGTimeStamp = dgvDataFlt.Rows(0).Cells("DateAndTime").Value 'for aktuelle lognings tidstempel
LOGDateStamp = Microsoft.VisualBasic.Left(LOGTimeStamp, 10)
LOGClockStamp = Microsoft.VisualBasic.Mid(LOGTimeStamp, 12, 5)
End If
I would suggest adding a class and then inheriting the DataGridView control into that class. I have made a quick little example of this and the code works, but to get it to work you will have to perform a few steps:
(1) If you don't already have a windows forms application to test this then,
make a new one.
(2) Create class named KeyedDataGridView
(3) Copy and Paste the following Code into KeyedDataGridView class
(4) Rebuild your Project
(5) Drag and Drop new component onto your windows Form.
NOTE: This class is limited, but should still be able to do what you require of it.
Finally, if you need any help then, please leave a comment and will try to get to it when I can.
Option Explicit On
Public Class KeyedDataGridView
Inherits Windows.Forms.DataGridView
Dim _Rows As KeyedDataRows
Public Shadows Property Rows As KeyedDataRows
Get
Return _Rows
End Get
Set(value As KeyedDataRows)
_Rows = value
End Set
End Property
Public Sub New()
Dim strName As String
strName = Me.Name
strName = MyBase.Name
_Rows = New KeyedDataRows(Me)
_Rows.Rows = MyBase.Rows
End Sub
Protected Overrides Sub Finalize()
_Rows = Nothing
MyBase.Finalize()
End Sub
End Class
Public Class KeyedDataRows
Inherits Windows.Forms.DataGridViewRowCollection
Dim _TagNames As Dictionary(Of String, Integer)
Dim _Rows As DataGridViewRowCollection
Dim _Cells As Dictionary(Of String, DataGridViewCellCollection)
Dim dgv As DataGridView
Default Public Overloads ReadOnly Property Item(strTagName As String) As DataGridViewRow
Get
Return _Rows.Item(Me.IndexFromName(strTagName))
End Get
End Property
Protected Friend Property Rows As DataGridViewRowCollection
Get
Return _Rows
End Get
Set(value As DataGridViewRowCollection)
_Rows = value
End Set
End Property
Public Property TagName(index As Integer) As String
Get
Return CStr(_TagNames.Item(index))
End Get
Set(value As String)
_TagNames.Item(index) = value
End Set
End Property
Public Sub New(tmp As DataGridView)
MyBase.New(tmp)
dgv = tmp
_TagNames = New Dictionary(Of String, Integer)
_Cells = New Dictionary(Of String, DataGridViewCellCollection)
End Sub
Public Shadows Sub Add(strTagName As String)
Dim intCurRow As Integer
If dgv.AllowUserToAddRows Then
intCurRow = _Rows.Count - 1
Else
intCurRow = _Rows.Count
End If
_TagNames.Add(strTagName, intCurRow)
_Rows.Add()
End Sub
Public Shadows Sub Add(strTagName As String, dataGridViewRow As DataGridViewRow)
Dim intCurRow As Integer
If dgv.AllowUserToAddRows Then
intCurRow = _Rows.Count - 1
Else
intCurRow = _Rows.Count
End If
_TagNames.Add(strTagName, intCurRow)
_Rows.Add(dataGridViewRow)
End Sub
Public Shadows Sub Add(count As Integer, strTagNames() As String)
Dim intI As Integer
Dim intCurRow As Integer
If dgv.AllowUserToAddRows Then
intCurRow = _Rows.Count - 1
Else
intCurRow = _Rows.Count
End If
For intI = 0 To (count - 1)
_TagNames.Add(strTagNames(intI), intCurRow)
_Rows.Add()
intCurRow = _Rows.Count - 1
Next intI
End Sub
Public Property IndexFromName(strTagName As String) As Integer
Get
If _TagNames.Count > 0 Then
If _TagNames.ContainsKey(strTagName) Then
Return _TagNames.Item(strTagName)
Else
Return -1
End If
Else
Return -1
End If
End Get
Set(value As Integer)
_TagNames.Add(strTagName, value)
End Set
End Property
Public Overloads Sub RemoveAt(strTagName As String)
_Cells.Remove(strTagName)
_Rows.RemoveAt(IndexFromName(strTagName))
_TagNames.Remove(strTagName)
End Sub
Protected Overrides Sub Finalize()
_TagNames.Clear()
_TagNames = Nothing
_Cells.Clear()
_Rows.Clear()
_Cells = Nothing
_Rows = Nothing
MyBase.Finalize()
End Sub
End Class
I also, added the following buttons to a windows form to test the code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
With KeyedDataGridView1
.Rows.Add("Tag Test 1")
.Rows.Add("Tag Test 2")
.Rows.Add("Tag Test 3")
.Rows.Add("Tag Test 4")
End With
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
MsgBox(KeyedDataGridView1.Rows("Tag Test 3").Cells(0).Value & vbCrLf &
KeyedDataGridView1.Rows("Tag Test 3").Cells(1).Value & vbCrLf &
KeyedDataGridView1.Rows("Tag Test 3").Cells(2).Value)
MsgBox(KeyedDataGridView1.Rows("Tag Test 2").Cells(0).Value & vbCrLf &
KeyedDataGridView1.Rows("Tag Test 2").Cells(1).Value & vbCrLf &
KeyedDataGridView1.Rows("Tag Test 2").Cells(2).Value)
MsgBox(KeyedDataGridView1.Rows("Tag Test 1").Cells(0).Value & vbCrLf &
KeyedDataGridView1.Rows("Tag Test 1").Cells(1).Value & vbCrLf &
KeyedDataGridView1.Rows("Tag Test 1").Cells(2).Value)
End Sub

VB.NET - Cannot bind to the new display member

I'm trying to assign the DataSource for a ComboBox that will allow the user to select a member. I'm receiving this error when run my application:
Cannot bind to the new display member.
Parameter name: newDisplayMember.
Here's my code:
Private Sub StartScreen_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'GetAllELData()
ddlMember.DataSource = GetMemberList()
ddlMember.DisplayMember = "DisplayName"
ddlMember.ValueMember = "ID"
End Sub
Private Function GetMemberList() As List(Of Member)
Dim rval = New List(Of Member)
Dim dv As DataView = New DataView
Dim myConnString = ConfigurationSettings.AppSettings("ConnString")
Try
dv = SqlHelper.ExecuteDataset(myConnString, CommandType.StoredProcedure, "spGetData").Tables(0).DefaultView
Catch ex As Exception
MessageBox.Show(ex.Message, "Database Error", MessageBoxButtons.OK)
End Try
For Each row As DataRowView In dv
Dim mbrNum As String = row.Item("IMMBR_CD").ToString()
Dim mbrName As String = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(row.Item("IMMBR_NM20").ToLower())
Dim mbrState As String = row.Item("IMMBR_ST").ToString()
'assigns the member data to the list of members
rval.Add(New Member(mbrNum, mbrName, mbrState))
Next
Return rval
End Function
And then my class definition:
Public Class Member
Public ID As String
Public Name As String
Public State As String
Public DisplayName As String
Public Sub New(ByVal i As String, ByVal n As String, ByVal s As String)
ID = i
Name = n
State = s
DisplayName = ID & " - " & Name & ", " & State
End Sub
Public Overrides Function ToString() As String
Dim rval As String = ID & " - " & Name & ", " & State
Return rval
End Function
Public Function GetID() As String
Return ID
End Function
Public Function GetName() As String
Return Name
End Function
Public Function GetState() As String
Return State
End Function
End Class
I don't know why I'm getting the error. The application correctly loads the member as intended and works just fine once I click "Continue" on the error popup. Everything I've found about the error is for people passing a table as their DataSource instead of a custom class like me and the answers contain only code snippets rather than an explanation of the why there's a problem.
Can anyone help me figure out what's wrong here?
Thanks a bunch!
The errors were caused by binding directly to the fields. Defining those as properties and binding to the properties solved the issue.
Public ReadOnly Property GetID() As String
Get
Return Me.ID
End Get
End Property
Public ReadOnly Property GetName() As String
Get
Return Me.Name
End Get
End Property
Public ReadOnly Property GetState() As String
Get
Return Me.State
End Get
End Property
Public ReadOnly Property GetDisplayName() As String
Get
Return Me.DisplayName
End Get
End Property
And:
Private Sub StartScreen_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'GetAllELData()
ddlMember.DataSource = GetMemberList()
ddlMember.DisplayMember = "GetDisplayName"
ddlMember.ValueMember = "GetID"
End Sub

Populating a combo box with a list of functions - Need Advice

I'm looking for some advice on the best way to handle this.
I have a list of about 200 "Functions" which are listed in a combo box. When the user selects a 'function' from the list, I need to return the functionID (integer).
I know this can be done easily by binding a dataset to the key and value of the combobox, I'm just not sure about the best way to populate the dataset.
I feel that the way I'm doing it currently is very convoluted:
I currently have a txt file as an embedded resource which I write to a temporary directory, then I use the following code to read in that text file and populate that box by setting the combobox's datasource and Display Member. It does this by way of a custom class which is implementing System.Collections.IList.
I have pasted the code below. The reason I want to simplify it is that I dislike writing the text file to the disk, because sometimes it fails.
I'm looking for a way to populate my combobox and return my ID, without writing anything to the user's temp folder.
I am open to changing the format of the embedded resource, and or the code.
The fnlist.txt is formatted currently as follows.
index, Function Name, ID
The index is only included for sorting (to keep NONE at the bottom, and unknown function at the top), and I suppose is not strictly required.
#Region "Function lookup"
Dim path As String = System.IO.Path.GetTempPath
Dim _objFnXtef As New clsFunctionXref(path & "fnList.txt")
Private Sub populate_list()
functionlist.DataSource = _objFnXtef
functionlist.DisplayMember = "StrFunction"
End Sub 'Populates the function list
Function get_index(ByVal fnid As Integer)
Dim iLookupNumber As Integer = fnid
Dim tmpFnInfo As New clsFunctionInfo
Dim iReturnIdx As Integer = -1
If iLookupNumber <> 0 Then
tmpFnInfo.IFunctionNumber = iLookupNumber
iReturnIdx = _objFnXtef.IndexOf(tmpFnInfo)
If iReturnIdx <> -1 Then
Return iReturnIdx - 1
Else
Return get_index(9999)
End If
End If
Return 0
End Function 'Returns index of specified function number
#End Region 'All function list functions
Here is the code when a user changes the drop down:
Private Sub functionlist_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles functionlist.SelectedIndexChanged
Dim iReturnFuctionID As Integer = 0
Dim tmpFnInfo As New clsFunctionInfo
tmpFnInfo = _objFnXtef(functionlist.SelectedIndex)
iReturnFuctionID = tmpFnInfo.IFunctionNumber
Func = (iReturnFuctionID)
End Sub
And here is the supporting class:
Imports Microsoft.VisualBasic.FileIO
Public Class clsFunctionInfo
Private _idxFunction As Integer
Public Property IdxFunction() As Integer
Get
Return _idxFunction
End Get
Set(ByVal value As Integer)
_idxFunction = value
End Set
End Property
Private _strFunction As String
Public Property StrFunction() As String
Get
Return _strFunction
End Get
Set(ByVal value As String)
_strFunction = value
End Set
End Property
Private _iFunctionNumber As Integer
Public Property IFunctionNumber() As Integer
Get
Return _iFunctionNumber
End Get
Set(ByVal value As Integer)
_iFunctionNumber = value
End Set
End Property
End Class
Public Class clsFunctionXref
Implements System.Collections.IList
Private _colFunctionInfo As New Collection
Private _filePath As String
Public Property FilePath() As String
Get
Return _filePath
End Get
Set(ByVal value As String)
_filePath = value
End Set
End Property
Public Sub New(ByVal filename As String)
_filePath = filename
Dim _idx As Integer = 1
Dim fields As String()
Dim delimiter As String = ","
Dim iFnx As Integer
Using parser As New TextFieldParser(filename)
parser.SetDelimiters(delimiter)
While Not parser.EndOfData
' Read in the fields for the current line
fields = parser.ReadFields()
Try
iFnx = Convert.ToInt16(fields(0).ToString)
Catch ex As Exception
MessageBox.Show("Error reading file. " & ex.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End Try
Dim objFunction As New clsFunctionInfo
objFunction.IdxFunction = _idx
objFunction.IFunctionNumber = iFnx
objFunction.StrFunction = fields(1).ToString
Me.Add(objFunction)
_idx += 1
End While
End Using
End Sub
Public Function Add(ByVal value As Object) As Integer Implements System.Collections.IList.Add
If _colFunctionInfo.Contains(value.IFunctionNumber.ToString) Then
SyncLock Me.SyncRoot
_colFunctionInfo.Remove(value.IFunctionNumber.ToString)
End SyncLock
ReIndex()
End If
SyncLock Me.SyncRoot
_colFunctionInfo.Add(value, value.IFunctionNumber.ToString)
End SyncLock
End Function
Public Sub Clear() Implements System.Collections.IList.Clear
SyncLock Me.SyncRoot
_colFunctionInfo.Clear()
End SyncLock
End Sub
Public Function Contains(ByVal value As Object) As Boolean Implements System.Collections.IList.Contains
If _colFunctionInfo.Contains(value.IFunctionNumber.ToString) Then
Return True
Else
Return False
End If
End Function
Public ReadOnly Property Count() As Integer Implements System.Collections.ICollection.Count
Get
Return _colFunctionInfo.Count
End Get
End Property
Public ReadOnly Property IsReadOnly() As Boolean Implements System.Collections.IList.IsReadOnly
Get
Return False
End Get
End Property
Public Sub Remove(ByVal value As Object) Implements System.Collections.IList.Remove
If _colFunctionInfo.Contains(value.IFunctionNumber.ToString) Then
SyncLock Me.SyncRoot
_colFunctionInfo.Remove(value.IFunctionNumber.ToString)
End SyncLock
ReIndex()
End If
End Sub
Public Function GetEnumerator() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
Return _colFunctionInfo.GetEnumerator
End Function
Public Sub Insert(ByVal index As Integer, ByVal value As Object) Implements System.Collections.IList.Insert
SyncLock Me.SyncRoot
If _colFunctionInfo.Contains(value.IFunctionNumber.ToString) Then
_colFunctionInfo.Remove(value.IFunctionNumber.ToString)
End If
If index < _colFunctionInfo.Count Then
_colFunctionInfo.Add(value, value.IFunctionNumber.ToString, index - 1)
Else
_colFunctionInfo.Add(value, value.IFunctionNumber.ToString)
End If
End SyncLock
ReIndex()
End Sub
Public Sub RemoveAt(ByVal index As Integer) Implements System.Collections.IList.RemoveAt
SyncLock Me.SyncRoot
If _colFunctionInfo.Count <= index And index > 0 Then
_colFunctionInfo.Remove(index)
End If
End SyncLock
ReIndex()
End Sub
Private Sub ReIndex()
SyncLock Me.SyncRoot
Dim iReIndex As Integer = 1
Dim colTemp As New Collection
For Each obj As clsFunctionInfo In _colFunctionInfo
obj.IdxFunction = iReIndex
colTemp.Add(obj, obj.IFunctionNumber)
iReIndex += 1
Next
_colFunctionInfo.Clear()
For Each obj1 As clsFunctionInfo In colTemp
_colFunctionInfo.Add(obj1, obj1.IFunctionNumber.ToString)
Next
colTemp.Clear()
End SyncLock
End Sub
Public ReadOnly Property IsSynchronized() As Boolean Implements System.Collections.ICollection.IsSynchronized
Get
Return True
End Get
End Property
Public ReadOnly Property SyncRoot() As Object Implements System.Collections.ICollection.SyncRoot
Get
Dim _syncRoot As New Object
Return _syncRoot
End Get
End Property
Public ReadOnly Property IsFixedSize() As Boolean Implements System.Collections.IList.IsFixedSize
Get
Return False
End Get
End Property
Public Sub CopyTo(ByVal array As System.Array, ByVal index As Integer) Implements System.Collections.ICollection.CopyTo
For Each obj As clsFunctionInfo In _colFunctionInfo
array(index) = obj
index += 1
Next
End Sub
Public Function IndexOf(ByVal value As Object) As Integer Implements System.Collections.IList.IndexOf
SyncLock Me.SyncRoot
Dim tmpFnInfo As New clsFunctionInfo
Dim tmpFunctionNumber As Integer
Dim tmpidx As Integer = -1
tmpFnInfo = DirectCast(value, clsFunctionInfo)
tmpFunctionNumber = tmpFnInfo.IFunctionNumber
For Each obj In _colFunctionInfo
tmpFnInfo = DirectCast(obj, clsFunctionInfo)
If tmpFunctionNumber = tmpFnInfo.IFunctionNumber Then
tmpidx = tmpFnInfo.IdxFunction
Exit For
End If
Next
Return tmpidx
End SyncLock
End Function
Default Public Property Item(ByVal index As Integer) As Object Implements System.Collections.IList.Item
Get
index += 1
Return _colFunctionInfo(index)
End Get
Set(ByVal value As Object)
End Set
End Property
End Class
I'm sorry that this is so long, but I know that someone on here has some great suggestions on how to handle this because I'm having a little trouble wrapping my head around it. I think I've been starring at it too long.
since you have the text file as an embedded resource, you can open a stream to the file from there, without having to write it to disk. The ResourceReader class should help you.

Parse Control name to Variable name

I have a var called as "Cheat_Enabled":
Dim Cheat_Enabled As Boolean
And a Checkbox called as "CheckBox_Cheat" with the tag "Cheat"
Now I want to do a dynamic method to change the value of the var by spliting (or something) the name of the control.
For example, something like this (the code obviouslly don't work):
Private Sub CheckBoxes_CheckedChanged(sender As Object, e As EventArgs) Handles _
CheckBox_Cheat.CheckedChanged
Dim SenderVarEquivalent As Object = _
Me.variables.Find(sender.Tag & "_Enabled")(0)
If sender.Checked Then SenderVarEquivalent = True _
Else SenderVarEquivalent = False
End Sub
' Info:
' Sender.Tag = "Cheat"
' Sender.Name = "CheckBox_Cheat"
' VariableName = "Cheat_Enabled"
I think this can be done with one CType or DirectCast or GetObject but I don't know exactly how to do it.
UPDATE:
This is a similar easy code but instead of converting ControlName to VariableName it is converting the control tag to the ControlName Object of the Checkbox:
Public Class Form1
Dim Cheat_Enabled As Boolean = True
Private Sub CheckBox_Cheat_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox_Cheat.CheckedChanged
CType(Controls("CheckBox" & "_" & sender.tag), CheckBox).Checked = Cheat_Enabled
End Sub
End Class
I hope if I can do the same to CType the control name to catch the variablename and use it, for example like this:
Dim Cheat_Enabled As Boolean
Private Sub CheckBox_Cheat_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox_Cheat.CheckedChanged
' Sender.name is : "CheckBox_Cheat"
' Sender.tag is : "Cheat"
' Variable name is: "Cheat_Enabled"
If sender.checked Then
CType(Variable(sender.tag & "_Enabled"), Boolean) = True
Else
CType(Variable(sender.tag & "_Enabled"), Boolean) = False
End If
End Sub
In MSDN you can find a VB.Net example how to enumerate all members of a given class:
Imports System
Imports System.Reflection
Imports Microsoft.VisualBasic
Class MyFindMembersClass
Public Shared Sub Main()
Dim objTest As New Object()
Dim objType As Type = objTest.GetType()
Dim arrayMemberInfo() As MemberInfo
Try
'Find all static or public methods in the Object
'class that match the specified name.
arrayMemberInfo = objType.FindMembers(MemberTypes.Method, _
BindingFlags.Public Or BindingFlags.Static _
Or BindingFlags.Instance, _
New MemberFilter(AddressOf DelegateToSearchCriteria), _
"ReferenceEquals")
Dim index As Integer
For index = 0 To arrayMemberInfo.Length - 1
Console.WriteLine("Result of FindMembers -" + ControlChars.Tab + _
arrayMemberInfo(index).ToString() + ControlChars.Cr)
Next index
Catch e As Exception
Console.WriteLine("Exception : " + e.ToString())
End Try
End Sub 'Main
Public Shared Function DelegateToSearchCriteria _
(ByVal objMemberInfo As MemberInfo, _
ByVal objSearch As Object) As Boolean
' Compare the name of the member function with the filter criteria.
If objMemberInfo.Name.ToString() = objSearch.ToString() Then
Return True
Else
Return False
End If
End Function 'DelegateToSearchCriteria
End Class 'MyFindMembersClass
Another alternative would be to put all your boolean variables into one Dictionary object. This would allow you to access the boolean values "by name" without using Reflection.
Example for illustration:
Imports System.Collections.Generic
Module vbModule
Class Example
Private _dictionary
Public Sub New()
' Allocate and populate the field Dictionary.
Me._dictionary = New Dictionary(Of String, Boolean)
Me._dictionary.Add("v1", False)
Me._dictionary.Add("v2", True)
End Sub
Public Function GetValue(name as String) As Boolean
' Return value from private Dictionary.
Return Me._dictionary.Item(name)
End Function
Public Sub SetValue(name as String, val as Boolean)
Me._dictionary.Item(name) = val
End Sub
End Class
Sub Main()
' Allocate an instance of the class.
Dim example As New Example
' Write a value from the class.
Console.WriteLine(example.GetValue("v1"))
Console.WriteLine(example.GetValue("v2"))
example.SetValue("v1", true)
Console.WriteLine(example.GetValue("v1"))
End Sub
End Module

VB.Net Create Extension As DataTable(Index)

I have a question related with VB.Net Code.
I see that the DataTable we can use:
DataTable(0) ' This return a DataRow with the selected index
In the intellisense I see that this functionality can achieve with a extension... but, If I create a extension, always I need refer the Extension before to use it
Public Module asdadsdas
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)>
<System.Runtime.CompilerServices.ExtensionAttribute()>
Friend Function MyExt(ByVal pMyObject As MyObject, ByVal ColumnName As String) As MyObject.ColumnData
Return pMyObject.Columns(0)
End Function
End Module
Public Class MyObject
Friend Structure ColumnData
Friend vNombre As String
Friend vApellido As String
Friend vTelefono As String
Public Property Nombre As String
Get
Return Me.vNombre
End Get
Set(ByVal value As String)
Me.vNombre = value
End Set
End Property
End Structure
Friend Columns() As ColumnData
Public Sub add(ByVal MyColumn As String)
ReDim Columns(0)
Columns(0).vNombre = MyColumn
End Sub
End Class
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim Test As New MyObject
Test.add("TEST 001")
' HERE IS THE PROBLEM
Test("TEST 001")
' CORRECT USE
Test.MyExt("TEST 001")
End Sub
End Class
Now, my concrete question: How I can make a default extension in a specific Object?
#competent_tech: man you are a genius... thanks by your comment!
This is the solution of my problem:
Public Class ColumnData
Friend Name As String
Friend LastName As String
Friend Phone As String
End Class
Public Class MyColumns
Friend Data() As ColumnData
Default Property Item(ByVal ColumnName As String) As ColumnData
Get
Return Data(0)
End Get
Set(ByVal value As ColumnData)
End Set
End Property
Public Sub add(ByVal Name As String, ByVal LastName As String, ByVal Phone As String)
If Data Is Nothing Then
ReDim Data(0)
Data(0) = New ColumnData
End If
With Data(0)
.Name = Name
.LastName = LastName
.Phone = Phone
End With
End Sub
End Class
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim Test As New MyColumns
Test.add("Name 001", "bolanos.m", "500-2004-1000")
Debug.Print(Test("Name 001").LastName & " - " & Test("Name 001").Phone)
' bolanos.m - 500-2004-1000
Test("Name").LastName = "BOLANOS.M MODIFY"
Debug.Print(Test("Name 001").LastName & " - " & Test("Name 001").Phone)
' BOLANOS.M(MODIFY - 500 - 2004 - 1000)
End Sub
End Class
Why not just add default properties to the MyObject class?
Default Public Property IndexedColumn(index As String) As ColumnData
Get
Return Columns(index)
End Get
Set(value As ColumnData)
Columns(index) = value
End Set
End Property
Default Public Property IndexedColumn(index As Integer) As ColumnData
Get
Return Columns(index)
End Get
Set(value As ColumnData)
Columns(index) = value
End Set
End Property
You will need to change the exposure level of the structure and the access will be:
Dim oColumnData = Test("TEST 001")