Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
ASP.NET
VB.Net
C-Sharp
SQL Server
 

Features of arrays using Visual Basic .NET.

Author: DevASP
Download Source Code : 568_Arrays Using VB.Net.zip

In this Article I will explain you the way in which we can Create and Utilize the arrays using VB.net.

The application shows how to work with an array of value types, strings, and an array of reference types, a custom Customer object. The Customer object exposes public Id and Name fields. There are six command buttons which execute various procedures.

  • Create Static Array—this procedure will create an array using the new {} syntax to load an array of values. The Array of group box provides an option for loading the array with strings or objects (Customer) instances. Once the array is loaded, it is passed to a support procedure, DisplayArrayData, which enumerates through the array and puts the values in Data As Loaded list box. 

  

  • Sort—this procedure loads the data using the same code as in the Create Static Array example. However, once the data is loaded, the shared method Sort from the Array class is applied the data is loaded into the lstAfter list box control.

 

  • Reverse—this procedure works just like Sort except it sorts the data in the reverse order of which the data was loaded.

 

  • Binary Search—performing a binary search requires that array be sorted first. So after the data is loaded into the array, it is sorted, and then a binary search is performed. The value provided in text box labeled Search For is used as the search criteria. If the item is found, then its index position is displayed. If the item is not found, the Array.BinarySearch function returns the bitwise complement of where the item would have been if it existed.

 

  • Create Dynamic Array—this procedure uses the numeric value provided in the text box txtLength to ReDim an array. It the loops through each new element and displays an InputBox requested a value for the item. After which, that data is loaded into a list box.

 

  • Create Matrix Array—this procedure builds a static two dimensional array that contains two columns, and three rows and then displays it in a list box.

Note that in order to keep the code isolated, each array is built at the procedure level each time you click one of the buttons.

For the Proper Understanding. Follow the steps below.

1. Create new application Using File menu and Choose vb.net project.

Now you will see the form Open in your application.

2. Now write the region of code below.

 

Write the Code against the click Event of Button. That event Actually do some important tasks like it Make sure there is a value to use a search criteria. Sort the array otherwise the BinarySearch method won't work. Show the data sorted.If the item is not found, a negative number is returned. This is the bitwise complement for the location where the

item would have been *if* it existed. We use the Not operator to flip it back to a postive number. When searching an array of objects, we need to use a compatible object type. In this case we're using the value provided by the txtBSearchFor box as the customer's name and providing a bogus Id value. The key to binary search working with objects is that the object must implement IComparable.

 

 

 

Private Sub cmdBinarySearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdBinarySearch.Click

                        Dim strMsg As String

                        Dim intPos As Integer

                        If Me.txtBSearchFor.Text.Length = 0 Then

                                    MessageBox.Show("Please enter a value to search for", "Binary Search", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

                                    Me.txtBSearchFor.Select()

                                    Exit Sub

                        End If

 

                        Dim strDataToFind As String = Me.txtBSearchFor.Text

                        Me.lstAfter.Items.Clear()

 

                        If Me.optStrings.Checked Then

                                    Dim strData() As String = {"Joe Hasterman", "Ted Mattison", "Joe Rummel", "Brian Gurnure", "Doug Landal"}

 

                                    Array.Sort(strData)

                                    DisplayArrayData(strData)

 

                                    intPos = Array.BinarySearch(strData, strDataToFind)

 

                                    If intPos > 0 Then

                                                strMsg = String.Format("The value {0} was found in the array at position {1}.", strDataToFind, intPos.ToString())

                                    Else

                                                Dim intBWC As Integer = (Not intPos)

 

                                                If intBWC = 0 Then

                                                            strMsg = String.Format("The value {0} was NOT found in the array. If it did exist it would be at position {1} before {2}", strDataToFind, intBWC.ToString(), strData(1))

                                                Else

                                                            Dim strItems() As String = {strDataToFind, intBWC.ToString(), strData(intBWC - 1), strData(intBWC)}

                                                            strMsg = String.Format("The value {0} was NOT found in the array. If it did exist it would be at position {1} between {2} and {3}.", strItems)

                                                End If

                                    End If

 

                                    MessageBox.Show(strMsg, "Binary Search Results", MessageBoxButtons.OK, MessageBoxIcon.Information)

                        Else

 

                                    Dim objData() As Customer = {New Customer(3423, "Joe Hasterman"), New Customer(9348, "Ted Mattison"), New Customer(3581, "Joe Rummel"), New Customer(7642, "Brian Gurnure"), New Customer(2985, "Doug Landal")}

 

                                    Array.Sort(objData)

 

                                    DisplayArrayData(objData)

                                    Dim c As New Customer(1, Me.txtBSearchFor.Text)

 

                                    intPos = Array.BinarySearch(objData, c, Nothing)

 

                                    If intPos > 0 Then

                                                strMsg = String.Format("The value {0} was found in the array at position {1}.", strDataToFind, intPos.ToString())

                                    Else

                                                Dim intBWC As Integer = (Not intPos)

 

                                                If intBWC = 0 Then

                                                            strMsg = String.Format("The value {0} was NOT found in the array. If it did exist it would be at position {1} before {2}", strDataToFind, intBWC.ToString(), objData(1).Name)

                                                Else

                                                            Dim strItems() As String = {strDataToFind, intBWC.ToString(), objData(intBWC - 1).name, objData(intBWC).name}

                                                            strMsg = String.Format("The value {0} was NOT found in the array. If it did exist it would be at position {1} between {2} and {3}.", strItems)

                                                End If

                                    End If

 

                                    MessageBox.Show(strMsg, "Binary Search Results", MessageBoxButtons.OK, MessageBoxIcon.Information)

                        End If

End Sub

 

This routine builds a dynamic array using the value specified in txtLength to set the number of buckets.

 

Private Sub cmdCreateDynamic_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCreateDynamic.Click

                        If Me.optStrings.Checked Then

                                    Dim strDynamicData() As String

                                    ReDim strDynamicData(System.Convert.ToInt32(Me.txtLength.Text) - 1)

                                    Dim i As Integer

                                    Dim strInput As String

                                    For i = 0 To strDynamicData.Length - 1

                                                strDynamicData(i) = InputBox("Enter a string", i.ToString(), "None " & i)

                                    Next

                                    DisplayArrayData(strDynamicData)

                        Else

                                    Dim strDynamicData() As Customer

                                    ReDim strDynamicData(System.Convert.ToInt32(Me.txtLength.Text) - 1)

                                    Dim i As Integer

                                    Dim strInput As String

 

                                    For i = 0 To strDynamicData.Length - 1

                                                strDynamicData(i) = New Customer()

                                                strDynamicData(i).Id = ((i + 1) * 10)

                                                strDynamicData(i).Name = InputBox("Enter a string", ("Item " & (i + 1)), ("None " & i + 1))

                                    Next

 

                                    DisplayArrayData(strDynamicData)

                        End If

            End Sub

 

This procedure uses the new initialization syntax to create a simple matrix array.

 

Private Sub cmdCreateMatrix_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCreateMatrix.Click

                       

                        Dim strMatrix(,) As String = {{"Bob", "Carol"}, {"Ted", "Alice"}, {"Joe", "Lisa"}}

                        Me.DisplayArrayData(strMatrix)

End Sub

This procedure uses the new initialization to build either a static array of strings or an array of Customer objects. Note that the arrary could of course be resized using the ReDim staetment. This command here takes advantage of the fact that objects in .NET can have parameterized constructors. This allows us to specify an array of objects in one line of code.

 

Private Sub cmdCreateStatic_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCreateStatic.Click

                        If Me.optStrings.Checked Then

                                    Dim strData() As String = {"Joe Hasterman", "Ted Mattison", "Joe Rummel", "Brian Gurnure", "Doug Landal"}

                                    DisplayArrayData(strData)

                        Else

                                    Dim objData() As Customer = {New Customer(3423, "Joe Hasterman"), New Customer(9348, "Ted Mattison"), New Customer(3581, "Joe Rummel"), New Customer(7642, "Brian Gurnure"), New Customer(2985, "Doug Landal")}

                                    DisplayArrayData(objData)

                        End If

            End Sub

 

 

In order for this procedure to work, the items contained in the array must support comparsion. This is accomplished by objects by implementing the IComparable interface. See the Customer object definition below for more information.

 

Private Sub cmdSort_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSort.Click

 

 

                        Me.lblDataAfter.Text = "Data After Sort"

 

                        If Me.optStrings.Checked Then

                                    Dim strData() As String = {"Joe Hasterman", "Ted Mattison", "Joe Rummel", "Brian Gurnure", "Doug Landal"}

                                    Array.Sort(strData)

                                    DisplayArrayData(strData, WhichListBox.BoxTwo)

                        Else

                                    Dim objData() As Customer = {New Customer(3423, "Joe Hasterman"), New Customer(9348, "Ted Mattison"), New Customer(3581, "Joe Rummel"), New Customer(7642, "Brian Gurnure"), New Customer(2985, "Doug Landal")}

                                    Array.Sort(objData)

                                    DisplayArrayData(objData, WhichListBox.BoxTwo)

                        End If

            End Sub

 

Normally ToString returns the fully qualified typename. In this example it would be NET.HowTo.Arrays.Customer We are overriding it so that we can return a simple display string when we're added to a list box.

 

Public Overrides Function ToString() As String

                        Return String.Format("Id={0}, Name={1}", Me.Id, Me.Name)

            End Function

 

Running the Sample

Changing the Array of option from Strings to Objects will enable Field to use for Sorts which controls whether an array of Customer objects is sorted by the Customer's Name field or Id field. In order for sorting or searching of an arry of objects to work, the object needs to implement the IComparable interface. This interface exposes a single method CompareTo. CompareTo simply evaluates the passed in object reference to itself using any criteria that makes since to the object. If the object passed in equals the current object, the 0 is returned. If the object is less than the current object, return 1, otherwise -1. The Customer object uses its name field as the test value to determine object equivalence. Optionally, the shared method SetCompareKey can be called before a sort is performed to change the field used.

 

 

   
Add Article Comment:
Name :
Email Address :
   
Comments :
 
   
<< Error Handling in VB.Net as(Try,Catch,Finally).

Disclaimer - Privacy
© 2002-2017 DevASP.net