tags:

views:

103

answers:

3

I have to set GridView.DataKeyNames (This is really a question about the syntax for a string array, in VB.Net.)

I am discovering the PrimaryKey columns names from within a loop, ie:

For Each fld As IEntityField In Me.llbDataSource.EntityCollection(0).PrimaryKeyFields
   'fld.Name  ' this is where the column name is stored, so I have to get this into an array
Next

I can not use this syntax.

GridView.DataKeyNames = new string() { "PowRatHP", "Voltage", "Phases", "Poles", "Drive" }

So, basically, how does one declare a string array (as required by GridView.DataKeyNames), and then populate the elements of the array from within a loop?

A: 

This is one way, bot not terribly elegant....

Dim dataKeyNames As String = ""
For Each fld As IEntityField In Me.llbDataSource.EntityCollection(0).PrimaryKeyFields
    If dataKeyNames <> "" Then dataKeyNames &= ","
    dataKeyNames &= fld.Name
Next
Me.grid.DataKeyNames = dataKeyNames.Split(",".ToCharArray())
tbone
A: 

To declare an array in VB.net, use

Dim stringArray(size) as String

Then you can do whatever you need to it.

Barry
I don't necessarily know the size....also, I'm not 100% sure if that is the type of array DataKeyNames expects.....
tbone
+1  A: 

If the only point of the loop is to collect the names, just use LINQ:

GridView.DataKeyNames = llbDataSource.EntityCollection(0).PrimaryKeyFields.Select(Function(f) f.Name).ToArray()

Or:

GridView.DataKeyNames = (From f in llbDataSource.EntityCollection(0).PrimaryKeyFields Select f.Name).ToArray()

Or, just add them to a List():

Dim l as New List(Of String)()
For Each fld As IEntityField In Me.llbDataSource.EntityCollection(0).PrimaryKeyFields
   l.Add(fld.Name)
Next
GridView.DataKeyNames = l.ToArray()

Or, an array:

Dim l(Me.llbDataSource.EntityCollection(0).PrimaryKeyFields.Count - 1) as String
For i as Integer = 0 to l.Length - 1
  l(i) = Me.llbDataSource.EntityCollection(0).PrimaryKeyFields(i).Name
Next
GridView.DataKeyNames = l
Mark Brackett
Wow, a smorgasbord of solutions, thanks!
tbone