How to add items from combo box into array - vb.net

I want to add the following combobox items into the array called "Numbers". Below is what I have so far. How do I add each combobox item into the array? Thanks.
number.Items.Add("One")
number.Items.Add("Two")
number.Items.Add("Three")
number.Items.Add("Four")
number.Items.Add("Five")
number.Items.Add("Six")
number.Items.Add("Seven")
Dim Numbers(6) As String
Dim count As Integer
For count= 0 To 6
Numbers(count) = number.Text
Next count

Try this code (it convert all items to array of string, so You can skip defining array size) :
number.Items.Add("One")
number.Items.Add("Two")
number.Items.Add("Three")
number.Items.Add("Four")
number.Items.Add("Five")
number.Items.Add("Six")
number.Items.Add("Seven")
'convert all items to string array
Dim Numbers = number.Items.Cast(Of String).ToArray()

you're very nearly there..
Dim Numbers(6) As String
Dim count As Integer
For count = 0 To 6
Numbers(count) = Number.Items(count).ToString
Next count
End Sub

I would use CopyTo() built-in method
Dim Numbers(ComboBox1.Items.Count - 1) As String
ComboBox1.Items.CopyTo(Numbers, 0)

The usual way round would be to put the items into an array and then either use that as the datasource for the combobox or simply add them with .AddRange:
Public Class Form1
Dim numbers As String()
Private Sub SetUpNumberComboBox()
numbers = {"One", "Two", "Three", "Four", "Five", "Six", "Seven"}
number.Items.AddRange(numbers)
' alternatively:
'number.DataSource = numbers
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SetpUpNumbersComboBox()
End Sub
End Class
[For anyone who uses the designer to add items, that way, you don't need to go through the (relatively) fiddly designer to change the items, you just edit the code.]

Related

Need help sorting ListView items by date for Order History

This is how the Order History looks like:
What I want to do is sort the items in this ListView by Date.
So far, I can't find any useful resource materials where I can sort the items by date.
Private Sub frmOrderHistory_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim orders As String = WindowsApplication1.Class1.Orders
Dim arrCheck(3) As String
Dim lineNum As Integer = -1
For Each i As String In System.IO.Directory.GetFiles(orders)
Dim a, c As String
a = System.IO.Path.GetFileNameWithoutExtension(i)
c = System.IO.Path.GetFullPath(i)
For Each line As String In File.ReadLines(c)
lineNum = lineNum + 1
ListView1.Items.Add(a)
arrCheck = Split(line, ",")
ListView1.Items(lineNum).SubItems.Add(arrCheck(0))
ListView1.Items(lineNum).SubItems.Add(arrCheck(1))
Next
Next
End Sub
The solution to your problem is to create list of objects which you want to display in the list view, sort the listview as per the requirement and then use the sorted list to the display in the list view.
I suggest to create a class Order to collect the order details from the file. Create list of orders and sort the list and then display it in the list view as following.
Following is the class Order.
Public Class Order
Public Property OrderDate() As DateTime
Get
Return m_OrderDate
End Get
Set
m_OrderDate = Value
End Set
End Property
Private m_OrderDate As DateTime
Public Property Item() As String
Get
Return m_Item
End Get
Set
m_Item = Value
End Set
End Property
Private m_Item As String
Public Property Price() As Double
Get
Return m_Price
End Get
Set
m_Price = Value
End Set
End Property
Private m_Price As Double
End Class
Following is the code of list binding.
Private Sub frmOrderHistory_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim orders As String = WindowsApplication1.Class1.Orders
Dim arrCheck(3) As String
Dim orderList = New List(Of Order)()
For Each filePath As var In System.IO.Directory.GetFiles(orders)
Dim order = New Order()
order.OrderDate = DateTime.ParseExact(System.IO.Path.GetFileNameWithoutExtension(filePath), "dd-MM-yyyy", CultureInfo.InvariantCulture)
For Each line As var In System.IO.File.ReadAllLines(filePath)
arrCheck = line.Split(New Char() {","C})
order.Item = arrCheck(0)
order.Price = Convert.ToDouble(arrCheck(1))
orderList.Add(order)
Next
Next
Dim sortedOrder = orderList.OrderByDescending(Function([or]) [or].OrderDate).ToList()
For i As var = 0 To sortedOrder.Count - 1
listView1.Items.Add(sortedOrder(i).OrderDate.ToString("dd-MM-yyyy"))
listView1.Items(i).SubItems.Add(sortedOrder(i).Item)
listView1.Items(i).SubItems.Add(sortedOrder(i).Price.ToString("00.00"))
Next
End Sub
As you can observer this solution is not straight forward. It requires formatting of string to datetime and back to string. The same with double values. Also requires looping thru items more than once.
Simpler would be to use datagridview. It takes a few clicks to set columns and dataformats of columns if you use datagridview. And you can bind collection of orders directly to it without looping thru the collection as following.
DataGridView1.DataSource = sortedOrder;

How to create group alphabet gridview devexpress?

Can any one help me to create group alphabet gridview to look like this picture?
I've tried with this code, but rows are not grouped by alphabet.
Private Sub GridView1_CustomColumnDisplayText(sender As Object, e As CustomColumnDisplayTextEventArgs) Handles GridView1.CustomColumnDisplayText
If e.Column.FieldName = "CompanyName" AndAlso e.IsForGroupRow Then
Dim rowValue As String = GridView1.GetGroupRowValue(e.GroupRowHandle, e.Column)
Dim val As String = Microsoft.VisualBasic.Left(rowValue, 1)
e.DisplayText = val
End If
End Sub
There is no need to handle the CustomColumnDisplay text event handler to extract the first letter of the "CompanyName" value. Instead, simply set the GridColumn.GroupInterval property for the "CompanyName" GridColumn to "Alphabetical". For instance:
MyGridView.Columns("CompanyName").GroupInterval = ColumnGroupInterval.Alphabetical

VB.net Trying to get text between first and second slashs only

I am trying to retrive the value of the text between the first and second backslashes... but my coding skills have brought me this far and no futher.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim TEST As String = "ONE\TWO\TRHREE\FOR\FIVE"
Dim splitted = TEST.Split("\"c)
Dim values = splitted.Skip(1).Take(splitted.Length - 2).ToArray()
MsgBox(values)
End Sub
Use regular expressions
Dim TEST as String = "ONE\TWO\TRHREE\FOR\FIVE"
Dim matches As MatchCollection = Regex.Matches(TEST, "\\(.|\n)*?\\", RegexOptions.IgnoreCase)
Now if you want those values to come out in message boxes
For Each ma As Match In matches
MsgBox(ma.ToString.Trim({"\"c}))
Next
This will get you both "TWO" and "FOR". If you want just "TWO" then matches(0) is all you need.
Alternatively, if you just want to get the matches into an array in one line, then have each value of the array in a single message box:
Dim values = Regex.Matches(TEST, "\\(.|\n)*?\\").Cast(Of Match)().[Select](Function(m) m.Value).ToArray()
MsgBox(String.Join(", ", values))
Use the Split function. It will split on a string and store the separated values in an array. This is the easiest of all the answers here and is probably the most correct way of doing this.
This is the VB way of doing it:
Dim s() As String = Split("ONE\TWO\TRHREE\FOR\FIVE", "\")
MessageBox.Show(s(1))
And this is the .NET way of doing it:
Dim mainString As String = "ONE\TWO\TRHREE\FOR\FIVE"
Dim s() As String = mainString.Split("\")
MessageBox.Show(s(1))
If you want "Two" as result, this should be the simplest approach:
Dim allToken As String() = "ONE\TWO\TRHREE\FOR\FIVE".Split("\"c)
Dim relevantPart = allToken.Skip(1).Take(1)
Dim result As String = String.Concat(relevantPart) ' "Two"
If you don't want a single string but a String() use ToArray:
Dim result As String() = relevantPart.ToArray()
Side-Note: you can't output an array directly, you could use String.Join:
MsgBox(String.Join(", ", result)) ' f.e. comma separated

Vb 2010 how to split (explode) a string

Based on the code I provided I would like to explode a string into two. The code is working but only if SearchQuery contains two phrases.
Private Sub SearchTxt_PreviewKeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles SearchTxt.PreviewKeyDown
Dim SearchQuery As String = SearchTxt.Text
Dim MyString As System.String
MyString = SearchQuery
Dim OutPutArray() As System.String
OutPutArray = Split(MyString, " ", -1)
''MsgBox(OutPutArray(0)) - Working
MsgBox(OutPutArray(1)) ' error - Index was outside the bounds of the array.
end sub
An array is always zero based (every type of collection is), so OutPutArray(1) tries to access the second item not the first. If it contains only one you get the exception.
Instead you want: OutPutArray(0)
If you don't know if it contains two, check it:
Dim first As String = OutPutArray(0)
Dim second As String = Nothing
If OutPutArray.Length > 1 Then
second = OutPutArray(1)
End If
As an aside, i recommend to use .NET methods, so String.Split:
Dim OutPutArray As String() = MyString.Split() ' splits by white-spaces, tabs or newlines
or, if you only want to split by spaces:
Dim OutPutArray As String() = MyString.Split({" "}, StringSplitOptions.None)

VB 2010 array/write array to file

I'm close to getting this to work, but currently can't get any output to display in the listbox. I had it working, but needed to move some things around to get the join function to work.
In my program, a user enters input into a textbox and an array is displayed in a listbox based on what they type in. For example, if they type in "a", all foods (in the textfile that is connected to the program) that start with "a" will be displayed.
When there is output, I need to find a way to name this array (which is created based on what the user inputs) and join all of the items in the listbox (example: foods stacked on top of each other in the listbox will be shown at the bottom as a string).
I am posting the code that I have thus far; all of the errors that I'm getting (and potentially my logic errors) are just in the first public class until the end of the first if-next statement:
Public Class frmFoods
Dim foods() As String = IO.File.ReadAllLines("foods.txt")
Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
Dim Letter As String = txtLetter.Text.ToUpper
Dim smallerarray() As Array
Dim userarray As String
lstOutput.Items.Clear()
If IsNumeric(txtLetter.Text) = False Then
For Each food As String In foods
smallerarray = listfoods(Letter)
lstOutput.Items.Add(Letter)
userarray = Join(smallerarray, ", ")
lstOutput.Items.Add(userarray)
Next
ElseIf IsNumeric(txtLetter.Text) = True Then
MessageBox.Show("Please enter a letter.")
Else
MessageBox.Show("The text box is empty")
End If
End Sub
Function listfoods(ByVal letter As String) As String()
Dim foodarray(foods.Count - 1) As String
Dim counter As Integer = 0
For Each food As String In foods
If food.StartsWith(letter) Then
foodarray(counter) = food
counter += 1
End If
Next
ReDim Preserve foodarray(counter - 1)
Return foodarray
End Function
you need to save the results of the listfoods function in a dictionary or similar and associate it with a key if you want to 'Name' it, although its not clear why you need to do this
As for listing the foods starting with the particular letter, you just need to iterate your result of the function listfoods and separate each one by a comma don't you?
What you have now will create many lists of each food as you are getting the list of food beginning with a particular letter for each food.. As I understand the question you only need to do that once.
Example:
Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
Dim Letter As String = txtLetter.Text.ToUpper
Dim smallerarray() As Array
Dim userarray As String
lstOutput.Items.Clear()
If IsNumeric(txtLetter.Text) = False Then
'get all items from the file which begin with the letter the user chose
smallerarray = listfoods(Letter)
'add that letter to the output listbox
lstOutput.Items.Add(Letter)
'join all of the elements which begin with that letter
'into a single comma separated string
userarray = Join(smallerarray, ", ")
'add that string to the output
lstOutput.Items.Add(userarray)
ElseIf IsNumeric(txtLetter.Text) = True Then
MessageBox.Show("Please enter a letter.")
Else
MessageBox.Show("The text box is empty")
End If
End Sub
it would probably be useful for you to step through the code and see the values of the variable at each place and compare this with what you expect to see if you can see where the actual value differs from what your logically expect so you can start to identify where the issue is