I have a structure containing 47 fields.I also have a string that contains "|" delimited value . I want to populate the structure with the values in the string. The only solution that I can think of is below.However this involves hardcoding. Is there a better way to achieve the same via a loop or anything else
Dim lobjStructData As New SUB_PNDGORDR_QRY_RESP
Dim lstrarrStream As String() = pstrStream.Split(CChar("|"))
lobjStructData.ClientId = CType(lstrarrStream(0), Char())
lobjStructData.PortfolioId = CShort(lstrarrStream(1))
lobjStructData.Currency = CType(lstrarrStream(2), Char())
lobjStructData.ProductId = CType(lstrarrStream(3), Char())
lobjStructData.InstrumentClass = CShort(lstrarrStream(4))
lobjStructData.OrderSymbol = CType(lstrarrStream(5), Char())
lobjStructData.Qty = CDbl(lstrarrStream(6))
lobjStructData.QtyRemaining = CDbl(lstrarrStream(7))
lobjStructData.OrderPrice = CDbl(lstrarrStream(8))
lobjStructData.TriggerPrice = CDbl(lstrarrStream(9))
lobjStructData.Remarks = CType(lstrarrStream(10), Char())
lobjStructData.QtyDiscRem = CDbl(lstrarrStream(11))
lobjStructData.OrderDateTime = CInt(lstrarrStream(12))
lobjStructData.IntOrderNo = CDbl(lstrarrStream(13))
lobjStructData.OrderStat = CType(lstrarrStream(14), Char())
lobjStructData.DiscQty = CDbl(lstrarrStream(15))
lobjStructData.SerialNo = CInt(lstrarrStream(16))
lobjStructData.OpenCloseFlg = CInt(lstrarrStream(17))
lobjStructData.InstrumentId = CInt(lstrarrStream(18))
lobjStructData.ContractSeriesId = CInt(lstrarrStream(19))
lobjStructData.InstrumentType = CShort(lstrarrStream(20))
lobjStructData.BuySellInd = CShort(lstrarrStream(21))
lobjStructData.MinFillQty = CDbl(lstrarrStream(22))
lobjStructData.ExchId = CInt(lstrarrStream(23))
lobjStructData.OrderTyp = CShort(lstrarrStream(24))
lobjStructData.ValidityCond = CDbl(lstrarrStream(25))
lobjStructData.ExchTrdNo = CType(lstrarrStream(26), Char())
lobjStructData.IntTranscode = CShort(lstrarrStream(27))
lobjStructData.ValidityAttr = CInt(lstrarrStream(28))
lobjStructData.BosRefId = CInt(lstrarrStream(29))
lobjStructData.OriginatorId = CType(lstrarrStream(30), Char())
lobjStructData.Commision = CDbl(lstrarrStream(31))
lobjStructData.SolicitedFlg = CType(lstrarrStream(32), Char())
lobjStructData.OrderFamily = CType(lstrarrStream(33), Char())
lobjStructData.ReceiptTime = CInt(lstrarrStream(34))
lobjStructData.ExchShortSellFlag = CType(lstrarrStream(35), Char())
lobjStructData.cSourceFlag = CChar(lstrarrStream(36))
lobjStructData.extnno = CInt(lstrarrStream(37))
lobjStructData.sReceiptMode = CType(lstrarrStream(38), Char())
lobjStructData.sErrorMsg = CType(lstrarrStream(39), Char())
lobjStructData.cCoverUncover = CChar(lstrarrStream(40))
lobjStructData.fATOrderNo = CDbl(lstrarrStream(41))
lobjStructData.iQtyCond = CShort(lstrarrStream(42))
lobjStructData.iReserve2 = CChar(lstrarrStream(43))
lobjStructData.fInternalRefId = CDbl(lstrarrStream(44))
Well, you have a few redundancies here:
the data type you convert to (which is probably the same as the data type of the field),
the position in the array (which is the same as the order in which you write the statement),
the name of the result variable,
the name of the stream.
Let's try to get rid of them. We will remove (1) with method overloads, (2) with an auto-incremented position variable, (3) with a shorter variable name and (4) by extracting the conversion code into a method.
The following code is untested, but the idea should be obvious:
Public Function ParseStream(pstrStream As String) As SUB_PNDGORDR_QRY_RESP
Dim p As New Parser(pstrStream)
Dim r As New SUB_PNDGORDR_QRY_RESP()
With r
p.ParseField(.ClientId)
p.ParseField(.PortfolioId)
p.ParseField(.Currency)
...
End With
Return r
End Function
Private Class Parser
Public Sub New(pstrStream As String)
Me.lstrarrStream = pstrStream.Split("|"c)
End Sub
Private pos As Integer = 0
Private lstrarrStream As String()
Public Sub ParseField(ByRef field As Char())
field = CType(lstrarrStream(pos), Char())
pos += 1
End Sub
Public Sub ParseField(ByRef field As Short)
field = CShort(lstrarrStream(pos))
pos += 1
End Sub
... other ParseField overloads...
End Class
Related
Structure WeightElement
Dim LowPointer As Integer
Dim HighPointer As Integer
Dim Values As WeightedTrait()
Dim Num As Integer
End Structure
Structure WeightedTrait
Dim TraitName As String
Dim TraitNum As Integer
Dim WeightValue As Decimal
End Structure
Function ExtractWeights(ByRef Tree As WeightElement(), ByRef Category As Integer, ByRef Trait As Integer, ByVal NeedsTrait As Boolean)
Dim Pointer As Integer = 0
Dim NotFound As Boolean = True
While NotFound
If Tree(Pointer).Num = Category Then
NotFound = False
ElseIf Tree(Pointer).Num > Category Then
Pointer = Tree(Pointer).LowPointer
ElseIf Tree(Pointer).Num < Category Then
Pointer = Tree(Pointer).HighPointer
End If
End While
If NeedsTrait Then
NotFound = True
While NotFound
If Tree(Pointer).Num = Trait Then
NotFound = False
ElseIf Tree(Pointer).Num > Trait Then
Pointer = Tree(Pointer).LowPointer
ElseIf Tree(Pointer).Num < Trait Then
Pointer = Tree(Pointer).HighPointer
End If
End While
End If
Return Tree(Pointer).Values
End Function
Private Sub SaveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveToolStripMenuItem.Click
Dim Log(1) As WeightedTrait
Log(0).TraitName = "xxxx"
Log(0).TraitNum = 0
Log(0).WeightValue = 0
Dim Test(40) As WeightElement
Test(0).LowPointer = 1
Test(0).HighPointer = 2
Test(0).Num = 1
Test(0).Values = Log
Test(0).Values(0).TraitName = "1"
Test(1).LowPointer = 0
Test(1).HighPointer = 0
Test(1).Num = 0
Test(1).Values = Log
Test(1).Values(0).TraitName = "0"
Test(2).LowPointer = 0
Test(2).HighPointer = 0
Test(2).Num = 2
Test(2).Values = Log
Test(2).Values(0).TraitName = "2"
Test(20).LowPointer = 0
Test(20).HighPointer = 0
Test(20).Num = 3
Test(20).Values = Log
Test(20).Values(0).TraitName = "3"
MsgBox(ExtractWeights(Test, 0, -1, False)(0).TraitName)
End Sub
The function, when I run it with the sub below it, always seems to return the last element of the array with a displayable value. Here, it should go to the second element and output 0, yet it somehow makes its way up to 20, for no reason that I can see
I have no idea why it is doing this. Does anyone else know how I might fix this?
You are setting the Values property of each element of the Test array to the same instance of Log.
Test(0).Values = Log
Test(1).Values = Log
Test(2).Values = Log
Test(20).Values = Log
Then, for each one, you set the zeroth value of TraitName.
Test(0).Values(0).TraitName = "1"
Test(1).Values(0).TraitName = "0"
Test(2).Values(0).TraitName = "2"
Test(20).Values(0).TraitName = "3"
Since Values is the same array you're updating all of them to finally be on "3".
You need to create distinct instances of the array for this to work.
Try this:
Private Function CreateWeightedTraitArray(ByVal TraitName As String) As WeightedTrait()
Dim Log(0) As WeightedTrait
Log(0).TraitName = TraitName
Log(0).TraitNum = 0
Log(0).WeightValue = 0
Return Log
End Function
Private Sub SaveToolStripMenuItem_Click(sender As Object, e As EventArgs)
Dim Test(40) As WeightElement
Test(0).LowPointer = 1
Test(0).HighPointer = 2
Test(0).Num = 1
Test(0).Values = CreateWeightedTraitArray("1")
Test(1).LowPointer = 0
Test(1).HighPointer = 0
Test(1).Num = 0
Test(1).Values = CreateWeightedTraitArray("0")
Test(2).LowPointer = 0
Test(2).HighPointer = 0
Test(2).Num = 2
Test(2).Values = CreateWeightedTraitArray("2")
Test(20).LowPointer = 0
Test(20).HighPointer = 0
Test(20).Num = 3
Test(20).Values = CreateWeightedTraitArray("3")
MsgBox(ExtractWeights(Test, 0, -1, False)(0).TraitName)
End Sub
I am trying to create a structure that I can use to separate individual elements of a record in order to use their components. Each record consists of a record number, group, division, category, and 5 integer codes that will be used for various operations depending on their group, division, and categories. Whenever I try to pass a RecordType into my ArrayList I get the error as stated in the title of this question. I have tried looking at other questions that have this error, but none of the answers seemed to work. I have tried creating a separate class for the RecordType, but it says it cant be done with a public class type. Here is the data I am trying to separate and use:
65f8|gh|l1|9k|985|8437|7894|9495|3730|
4287|gh|w1|uk|7341|5638|7715|8906|698|
3s89|jk|w1|h7|225|487|2013|4328|4066|
62l5|lo|r5|9k|5103|9879|3448|2921|7581|
486p|lo|r5|uk|6882|9879|2672|1015|3160|
a597|lo|r6|m9|385|6915|3615|9195|9817|
1m36|hu|k8|h7|656|8064|3852|9110|9858|
And this is the code I have written. The comments are loops I have used to test certain parts of the code in excel.
Type RecordType
number As String
group As String
div As String
cat As String
code1 As Integer
code2 As Integer
code3 As Integer
code4 As Integer
code5 As Integer
End Type
Sub ProgramOne()
Dim fileName As String, textData As String, fileLine As String, rowList() As String, numOfRecords As Integer, someString As String
Dim rowNum As Integer, colNum As Integer, counter As Integer, counter2 As Integer, groupCount As Integer, divCount As Integer, catCount As Integer
Dim groupBool As Boolean, catBool As Boolean, divBool As Boolean, groupList As Object, divList As Object, catList As Object
Set groupList = CreateObject("System.Collections.ArrayList")
Set divList = CreateObject("System.Collections.ArrayList")
Set catList = CreateObject("System.Collections.ArrayList")
fileName = "/Users/Ricky/Desktop/project1Data.txt"
Open fileName For Input As #1
rowNum = 1
Dim records As Object
Set records = CreateObject("System.Collections.ArrayList")
Dim placeholder As RecordType
Do Until EOF(1)
numOfRecords = numOfRecords + 1
Line Input #1, fileLine
rowList = Split(fileLine, "|")
placeholder.number = rowList(0)
placeholder.group = rowList(1)
placeholder.div = rowList(2)
placeholder.cat = rowList(3)
placeholder.code1 = rowList(4)
placeholder.code2 = rowList(5)
placeholder.code3 = rowList(6)
placeholder.code4 = rowList(7)
placeholder.code5 = rowList(8)
records.Add (placeholder)
Loop
'Dim counter2 As Integer
'counter2 = 2
' For x = 0 To UBound(records) - LBound(records)
' Cells(counter2, 1) = records(x).group
' Cells(counter2, 2) = records(x).div
' counter2 = counter2 + 1
' Next
Close #1
'For x = 0 To UBound(records) - LBound(records)
divBool = False
catBool = False
groupCount = 0
divCount = 0
catCount = 0
'Dim GroupName As Variant
'For Each GroupName In groupList
' groupBool = False
' For num = 0 To UBound(records) - LBound(records)
' If CStr(records(num).group) = CStr(GroupName) Then
' groupBool = True
' End If
' If Not groupBool Then
' groupCount = groupCount + 1
' groupList(groupCount) = records(num).group
' End If
' Next num
'Next GroupName
counter = 0
counter2 = 0
For Each GroupName In records
For Each GroupName2 In groupList
If records(counter).group = groupList(counter2) Then
groupBool = True
End If
counter2 = counter2 + 1
Next GroupName2
If groupBool = False Then
Next GroupName
Cells(1, 1) = "Number of records: " & numOfRecords
Cells(1, 2) = "Number of Groups: " & groupCount
Cells(2, 1) = "records index: " & UBound(records) - LBound(records)
counter = 0
'For Each GroupName In groupList
' Cells(3, counter) = GroupName
' counter = counter + 1
'Next GroupName
End Sub
Add a new class module, call it Record, move your Type in there, make it Private, and then declare a private field of that type, and expose a Property Get and a Property Let for each member:
Option Explicit
Private Type TRecord
Number As String
Group As String
Division As String
Category As String
Codes(1 To 5) As Long
End Type
Private this As TRecord
Public Property Get Number() As String
Number = this.Number
End Property
Public Property Let Number(ByVal value As String)
this.Number = value
End Property
Public Property Get Group() As String
Group = this.Group
End Property
Public Property Let Group(ByVal value As String)
this.Group = value
End Property
Public Property Get Division() As String
Division = this.Division
End Property
Public Property Let Division(ByVal value As String)
this.Division = value
End Property
Public Property Get Category() As String
Category = this.Category
End Property
Public Property Let Category(ByVal value As String)
this.Category = value
End Property
Public Property Get Code(ByVal index As Long) As Long
Code = this.Codes(index)
End Property
Public Property Let Code(ByVal index As Long, ByVal value As Long)
this.Codes(index) = value
End Property
Now use instances of that class instead, and it should work fine.
For additional cool-factor, remove+export the class module, open it in Notepad, and set its VB_PredeclaredId attribute to True. Save, and re-import the module: now your class has a default instance, and with that you can have a factory method:
Public Function Create(ByVal pNumber As String, ByVal pGroup As String, ByVal pDivision As String, ByVal pCategory As String, ParamArray pCodes As Variant) As Record
With New Record
.Number = pNumber
.Group = pGroup
.Division = pDivision
.Category = pCategory
'todo assert number of parameters to prevent out-of-bounds error
Dim i As Long
For i = LBound(pCodes) To UBound(pCodes)
.Code(i) = pCodes(i)
Next
Set Create = .Self
End with
End Function
Public Property Get Self() As Record
Set Self = Me
End Property
Now the reader loop can look like this:
Do Until EOF(1)
numOfRecords = numOfRecords + 1
Line Input #1, fileLine
rowList = Split(fileLine, "|")
records.Add Record.Create(rowList(0), rowList(1), rowList(2), rowList(3), rowList(4), rowList(5), rowList(6), rowList(7), rowList(8))
Loop
Note that a class' default instance can be abused to hold global state (e.g. like the way some people use UserForm's default instances). That doesn't mean they should. Use default instances for "static" methods that belong to the type rather than an instance, and you'll do great.
Combined with interfaces, you could even simulate immutability, but I don't think you need to go there for this.
Use a class, name it cRecord
Option Explicit
Private Type RecordType
number As String
group As String
div As String
cat As String
code1 As Integer
code2 As Integer
code3 As Integer
code4 As Integer
code5 As Integer
End Type
Dim mElement As RecordType
Property Let number(nval As String)
mElement.number = nval
End Property
Property Let group(nval As String)
mElement.group = nval
End Property
Property Let div(nval As String)
mElement.div = nval
End Property
Property Let cat(nval As String)
mElement.cat = nval
End Property
Property Let code1(nval As String)
mElement.code1 = nval
End Property
Property Let code2(nval As String)
mElement.code2 = nval
End Property
Property Let code3(nval As String)
mElement.code3 = nval
End Property
Property Let code4(nval As String)
mElement.code4 = nval
End Property
Property Let code5(nval As String)
mElement.code5 = nval
End Property
and then change your code to
Dim placeholder As cRecord
Do Until EOF(1)
numOfRecords = numOfRecords + 1
Line Input #1, fileLine
rowList = Split(fileLine, "|")
Set placeholder = New cRecord
placeholder.number = rowList(0)
placeholder.group = rowList(1)
placeholder.div = rowList(2)
placeholder.cat = rowList(3)
placeholder.code1 = rowList(4)
placeholder.code2 = rowList(5)
placeholder.code3 = rowList(6)
placeholder.code4 = rowList(7)
placeholder.code5 = rowList(8)
records.Add placeholder
Loop`
I've been tasked with adding a filtering mechanism to a result set. I understand the basic concepts of filtering using the Where clause in Linq, however there HAS to be a better way to do this, right?
Scenario:
I have 5 filterable columns on my result set. I have to take into account all variations of these 5 filters at any given time. This means that I have to manually type out an If/ElseIf statement with 120 different variations!
Here's the general way of how things are going and I just simply need to ask: Is there a better, quicker way to do this?!
The Filters
ByVal SearchMxMID As Integer,
ByVal SearchProfile As Integer,
ByVal SearchCZ As String,
ByVal SearchTerm As Integer,
ByVal SearchFwMth As Integer
The course of the If statements
If SearchMxMID = 0
And SearchProfile = 0
And SearchCZ = "All"
And SearchTerm = 0
And SearchFwMth = 0 Then
Dim queryMM = (From a In DBPricingContext.tbl_Matrix_Margins
Where a.CompanyID = CInt(sCompanyID)
Order By a.Profile
Select a)
Return New StoreResult(queryMM)
ElseIf SearchMxMID > 0
And SearchProfile = 0
And SearchCZ = "All"
And SearchTerm = 0
And SearchFwMth = 0 Then
Dim queryMM = (From a In DBPricingContext.tbl_Matrix_Margins
Where a.CompanyID = CInt(sCompanyID) And a.MarGroupID = SearchMxMID
Order By a.Profile
Select a)
Return New StoreResult(queryMM)
ETC
ETC
ETC
120 total times for each combination of these 5 filters (whether they are blank or have values). Is there a quicker way i can do this, something maybe in 1 single Linq query?
If SearchMxMID > 0 Then a.MarGroupID = SearchMxMID Else DO NOT APPLY WHERE CLAUSE
???
You can chain the Where clauses and construct your query dynamically like this:
Dim query = DBPricingContext.tbl_Matrix_Margins.AsQueryable()
If compID > 0 Then
query = query.Where(Function(a) a.CompanyID = compID)
End If
If SearchMxMID > 0 Then
query = query.Where(Function(a) a.MarGroupID = SearchMxMID)
End If
...
query = query.OrderBy(Function(a) a.Profile)
This scales well with many columns, as there will be only one If-statement per column.
Note that I am using the extension method syntax and lambda expressions instead of the specialized LINQ query syntax. A call to Select is not necessary, if you are just selecting the parameter a itself.
If you are using LINQ-to-Objects instead of LINQ-to-some_database, then replace the AsQueryable() by AsEnumerable().
Linq queries are chainable. You could simply have a single if per your case and if it is true then add another where. ie (in C# but should be easy to follow for any .Net coder - or you can use Telerik's code converter and revise the code a bit):
string country = "Germany";
string city = "Berlin";
int? productId = 3;
var data = db.Customers;
var result = data.AsQueryable();
if (!string.IsNullOrEmpty(country))
{
result = result.Where(r => r.Country == country);
}
if (!string.IsNullOrEmpty(city))
{
result = result.Where(r => r.City == city);
}
if (productId.HasValue)
{
result = result
.Where(r =>
r.Orders.Any(o =>
o.OrderDetails
.Any(od => od.ProductID == productId.Value)));
}
Another way is to is to simply use a NULL or ... approach. ie:
Private Sub Main()
Dim country As String = "" '"Brazil"
Dim city As String = "" '"Sao Paulo"
Dim orderDate As System.Nullable(Of DateTime) = Nothing 'new DateTime(1996,8,28);
Dim data = Orders.Where(Function(c) _
String.IsNullOrEmpty(country) OrElse c.ShipCountry.StartsWith(country)) _
.Where(Function(c) String.IsNullOrEmpty(city) OrElse c.ShipCity.StartsWith(city)) _
.Where(Function(c) orderDate Is Nothing OrElse c.OrderDate = orderDate) _
.Select(Function(c) New Order() With { _
.OrderId = c.OrderID, _
.CustomerId = c.CustomerID, _
.OrderDate = c.OrderDate, _
.ShipCountry = c.ShipCountry, _
.ShipCity = c.ShipCity _
})
Dim f As New Form() With { .Text = "Query Results" }
Dim dgv As New DataGridView() With { .Dock = DockStyle.Fill }
f.Controls.Add(dgv)
dgv.DataSource = data.ToList()
f.ShowDialog()
End Sub
Public Class Order
Public Property OrderId() As Integer
Get
Return m_OrderId
End Get
Set
m_OrderId = Value
End Set
End Property
Private m_OrderId As Integer
Public Property OrderDate() As System.Nullable(Of DateTime)
Get
Return m_OrderDate
End Get
Set
m_OrderDate = Value
End Set
End Property
Private m_OrderDate As System.Nullable(Of DateTime)
Public Property CustomerId() As String
Get
Return m_CustomerId
End Get
Set
m_CustomerId = Value
End Set
End Property
Private m_CustomerId As String
Public Property ShipCountry() As String
Get
Return m_ShipCountry
End Get
Set
m_ShipCountry = Value
End Set
End Property
Private m_ShipCountry As String
Public Property ShipCity() As String
Get
Return m_ShipCity
End Get
Set
m_ShipCity = Value
End Set
End Property
Private m_ShipCity As String
End Class
Note: Code is Linq To SQL code. With EF this wouldn't be supported and you need to use the former approach.
You can also compose the queries in series using the LINQ syntax.
Dim TempQuery = (From a In DbPricingContext.tbl_Matrix_Margins
Where a.CompanyID = CInt(sCompanyID)
Select a)
If SearchMxMID > 0 Then
TempQuery = (From a In TempQuery
Where a.MarGroupID = SearchMxMID
Select a)
End If
'... Add your other conditions in here...
Return New StoreResult(From a In TempQuery Order By a.Profile Select a)
Use logic like SearchValue = DefaultValue OrElse SearchValue = PropertyValue
Dim result = DBPricingContext.tbl_Matrix_Margins.
Where(Function(a) a.CompanyID = CInt(sCompanyID)).
Where(Function(a) SearchMxMID = 0 OrElse a.MarGroupID = SearchMxMID)
And add other search conditions in the same way.
It will return all rows if SearchMxMID = 0 and return only matched rows if SearchMxMID <> 0
For accuracy result I will be used Nullable type
Where(Function(a) SearchMxMID.HasValue = False OrElse a.MarGroupID = SearchMxMID.Value)
You can implement a specification pattern. Something like this:
Sub Main()
Dim someList As New List(Of SomeClass)
Dim now As DateTime = DateTime.Now
someList.Add(New SomeClass() With {.Id = 1, .Title = "001", .EntryDate = now})
someList.Add(New SomeClass() With {.Id = 2, .Title = "002", .EntryDate = now.AddSeconds(10)})
someList.Add(New SomeClass() With {.Id = 3, .Title = "003", .EntryDate = now.AddSeconds(20)})
Dim idParam As Integer = 1
Dim titleParam As String = "" '"001"
Dim dateParam As DateTime = now
' first approach, one selector
Dim selector As Func(Of SomeClass, Boolean) = Function(item)
With item
Return ((idParam <= 0) OrElse (.Id = idParam)) AndAlso
((String.IsNullOrEmpty(titleParam)) OrElse (.Title = titleParam)) AndAlso
((dateParam.CompareTo(DateTime.MinValue) = 0) OrElse (.EntryDate = dateParam))
End With
End Function
Dim list = From o In someList Where selector(o) Select o
For Each o In list
Console.WriteLine(o)
Next
' second approach, one selector per parameter
Dim selectorId As Func(Of SomeClass, Boolean) = Function(item)
Return ((idParam <= 0) OrElse (item.Id = idParam))
End Function
Dim selectorTitle As Func(Of SomeClass, Boolean) = Function(item)
Return ((String.IsNullOrEmpty(titleParam)) OrElse (item.Title = titleParam))
End Function
Dim selectorEntryDate As Func(Of SomeClass, Boolean) = Function(item)
Return ((dateParam.CompareTo(DateTime.MinValue) = 0) OrElse (item.EntryDate = dateParam))
End Function
Dim list2 = From o In someList
Where
selectorId(o) AndAlso
selectorTitle(o) AndAlso
selectorEntryDate(o)
Select o
For Each o In list2
Console.WriteLine(o)
Next
Console.ReadLine()
End Sub
Public Class SomeClass
Public Property Id As Integer
Public Property Title As String
Public Property EntryDate As DateTime
Public Overrides Function ToString() As String
Return String.Format("Id:{0} Title:{1} EntryDate:{2}", Id, Title, EntryDate)
End Function
End Class
Hope this example helps you a bit.
I would like to format my listbox so that the output becomes something like this.
This is method, not in the main form tho:
Public Function GetSeatInfoStrings(ByVal choice As DisplayOptions,
ByRef strSeatInfoStrings As String()) As Integer
Dim count As Integer = GetNumOfSeats(choice)
If (count <= 0) Then
Return 0
End If
strSeatInfoStrings = New String(count - 1) {}
Dim StrReservation As String = ""
strSeatInfoStrings = New String(count - 1) {}
Dim i As Integer = 0 'counter for return array
'is the element corresponding with the index empty
For index As Integer = 0 To m_totNumOfSeats - 1
Dim strName As String = ""
Dim reserved As Boolean = Not String.IsNullOrEmpty(m_nameList(index))
'if the criteria below are not met, skip to add info in the array
If (choice = DisplayOptions.AllSeats) Or
(reserved And choice = DisplayOptions.ReservedSeats) Or
((Not reserved) And (choice = DisplayOptions.VacantSeats)) Then
If (reserved) Then
StrReservation = "Reserved"
strName = m_nameList(index)
Else
StrReservation = "Vacant"
strName = "..........."
End If
strSeatInfoStrings(i) = String.Format("{0,4} {1,-8} {2, -20} {3,10:f2}",
index + 1, StrReservation, strName, m_priceList(index))
i += 1
End If
Next
Return count
End Function
I don't know how to format the listbox as the strSeatInfoStrings(i) in the main form.
My listbox
This is what I've done
Private Sub UpdateGUI()
'Clear the listbox and make it ready for new data.
ReservationList.Items.Clear()
'size of array is determined in the callee method
Dim seatInfoStrings As String() = Nothing
Dim calcOption As DisplayOptions = DirectCast(cmbDisplayOptions.SelectedIndex, DisplayOptions)
Dim count As Integer = m_seatMngr.GetSeatInfoStrings(calcOption, seatInfoStrings)
If count > 0 Then
ReservationList.Items.AddRange(seatInfoStrings)
Else
ReservationList.Items.Add("Nothing to display!")
End If
Found the error! I forgot to call the UpdateGUI() in the IntializeGUI().
I am currently working on project in which i have to display IP Configuration to user in VB.Net Application.
I am using DataGridView to display IP Config to user.
But problem is Datagridview doesnt display anything in its row at all.
Image for proof
Here is the code
Public Sub MT_Validate_Msg(ByRef lbData() As Byte)
Dim lsAddr(3) As String
Dim lsMAC(5) As String
Dim lstConfig As TCP_SER_Config
If lbData.Length >= 256 Then
'Check Header Footer and Response Size
If lbData(0) = Asc("$") And lbData(1) = Asc("#") _
And lbData(254) = Asc("<") And lbData(255) = Asc(">") _
And lbData(2) = UDP_RESPONSE_SIZE And lbData(3) = 0 Then
gnDevice_Search_Count += 1
'MsgBox("Response Received")
lsAddr(0) = lbData(7).ToString
lsAddr(1) = lbData(9).ToString
lsAddr(2) = lbData(11).ToString
lsAddr(3) = lbData(13).ToString
lstConfig.IP = String.Join(".", lsAddr)
lsAddr(0) = lbData(15).ToString
lsAddr(1) = lbData(17).ToString
lsAddr(2) = lbData(19).ToString
lsAddr(3) = lbData(21).ToString
lstConfig.Subnet = String.Join(".", lsAddr)
lsAddr(0) = lbData(23).ToString
lsAddr(1) = lbData(25).ToString
lsAddr(2) = lbData(27).ToString
lsAddr(3) = lbData(29).ToString
lstConfig.Gateway = String.Join(".", lsAddr)
lstConfig.Alive_Time = lbData(31)
lsMAC(0) = Hex(lbData(33)).ToString
lsMAC(1) = Hex(lbData(34)).ToString
lsMAC(2) = Hex(lbData(35)).ToString
lsMAC(3) = Hex(lbData(36)).ToString
lsMAC(4) = Hex(lbData(37)).ToString
lsMAC(5) = Hex(lbData(38)).ToString
lstConfig.MAC = String.Join("-", lsMAC)
MT_FillGrid(lstConfig)
End If
End If
End Sub
Public Sub MT_FillGrid(ByRef lstTCPConfig As TCP_SER_Config)
Dim row As String() = New String() {gnDevice_Search_Count.ToString, lstTCPConfig.IP, lstTCPConfig.Subnet, _
lstTCPConfig.Gateway, lstTCPConfig.Alive_Time.ToString, lstTCPConfig.MAC}
GridDev_List.Rows.Add(row)
row = New String() {"1", "192.168.0.100", "255.255.255.0", "255.255.255.255", "60", "22-0B-3C-2D-00-01"}
GridDev_List.Rows.Add(row)
End Sub
Expecting a result like this, Where i am going wrong in code ?