.NET Blog

Tony Cavaliere

 
My Favourite Albums
  And the Grappa wins.
E-mail me Send mail
Add to Technorati Favorites AddThis Feed Button

Subscribe to Cynot Why Not


Recent posts

Disclaimer

Hey unlike other bloggers I stand by what I say but just in case. The opinions expressed herein are my own except on Tuesday when the second card is not turned up otherwise it ain't worth squat.

© Copyright 2010

Binding to an array of String: Where's my String?

This one has bothered me for some time. Here is the situation you have a simple array of strings and then you bind it to a DataGrid. What do you expect when the grid is rendered? Silly me I was expecting to see a bunch of strings. And what did I get, a grid with a single column containing a heading of Length and a list of values that represents the length of each string in the array.

What the heck is happening here?

Here is a code snippet that declares an array of String that is later bound to a DataGrid.


  Dim s As String() = {"hey", "man", "where's", "my", "string"}

  DataGridView1.DataSource = s.ToList


The DataGrid is displayed as

Where is my String DataGrid

So where are the strings? Behind the covers .NET is using reflection to inspect the String object and searches for all properties that have no parameters. Each of these properties is then displayed in the DataGrid; and you guessed it the only parameter-less property the String object exposes is Length.

Guess the movie

Hey, what do you like, the leg or the wing, Henry? Or do you still go for the old hearts and lungs?

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: VB.NET
Posted by CynotWhyNot on Monday, March 17, 2008 1:46 PM
Permalink | Comments (71) | Post RSSRSS comment feed

Does VB.NET have Collection Initializers?

The short answer is no, at least not in the same sense as C#. Here is a snippet on how to initialize a collection in C#.


  List<Phone> oPhone = new List<Phone> {

       new Phone { PersonId = 1, Number = "111.111.1111" },

       new Phone { PersonId = 2, Number = "222.222.2222" }

  };


As you can see , in C#, it is possible to initialize a collection in one line of code. To my knowledge, in VB.NET, it requires an additional line of code and the use of a built-in extension method.


  Dim arrPhone As Phone() = { _

       New Phone With {.PersonId = 1, .Number = "111.111.1111"}, _

       New Phone With {.PersonId = 2, .Number = "222.222.2222"} _

  }

  Dim phoneList As List(Of Phone) = arrPhone.ToList()

Guess the movie

Hey, listen, I want somebody good - and I mean very good - to plant that gun. I don't want my brother coming out of that toilet with just his dick in his hands, alright?

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: VB.NET
Posted by CynotWhyNot on Monday, March 17, 2008 12:28 PM
Permalink | Comments (72) | Post RSSRSS comment feed