Is CStr needed?

danfloun

Member
Joined
Apr 5, 2010
Messages
23
Programming Experience
Beginner
Hi,

If I use the following code, displaying the bf char array in the label on the form works fine, however if I use the listebox to display the result I get char[]array displayed.

VB.NET:
            Dim bf(15) As Char
            Do While sr.Peek() >= 0
            sr.Read(bf, 0, bf.Length)
         Loop
            lsStatus.Items.Add(bf)
            lbgip.Text = bf

So options;
Converting the bf ToString() works fine, as does conversion using CStr as in
VB.NET:
Dim bfs As String = bf.ToString()
lsStatus.Items.Add(bfs)

VB.NET:
Dim bfs As String = CStr(bf) 
lsStatus.Items.Add(bfs)

So, is there are way to display the result from the char array in the listbox without conversion, or is it fine to use either of the examples I've given.
I'd like to know the difference if any.

Thanking you.
Oh and I do use the MSDN website and the google monster all the time for research, but sometimes the info isn't always that understandable.

Danny
 
When you add an object to a ListBox, the default behaviour is to display the result of that object's ToString method. You can override that by setting the control's DisplayMember to the name of a property or column that contains the data you want to display. In the case of a Char array, there is no property that contains the data you want to display, so that's not an option. If you want to convert a Char array to a String, the most correct way would be:
VB.NET:
myString = New String(myCharArray)
You should be doing that for the Label too. Your first code snippet is relying on an implicit conversion, which means that you have Option Strict Off. You should turn Option Strict On for this and other projects as soon as possible and leave it On. It will force you to make explicit conversions where previously you relied on the system to convert implicitly. That takes a bit of getting used to but it will help you learn to write better code, your code will be faster and less error-prone.
 
Back
Top