-2

i am creating an array in vb.net:

Dim BoldRows() as String

im adding values to the array here:

Dim detail_table_row as Integer = 1
While reader.read
    detail_table_row = detail_table_row + 1

    BoldRows(detail_table_row) = detail_table_row
End While

this is inside a loop and detail_table_row is a different number everytime it loops

then outside of my loop i have:

For Each row As Integer In BoldRows
    oDoc_detail_table.Range.Rows(row).Range.Font.Bold = True
Next

but i am being told:

Variable 'BoldRows' is used before it has been assigned a value.
charlie
  • 637
  • 2
  • 23
  • 66
  • 1
    The error message is pretty clear: you never assigned anything to `BoldRows`. You only declared it. – rory.ap Dec 14 '15 at 21:59
  • its telling me this when i am trying to assign values to the array – charlie Dec 14 '15 at 22:00
  • 1
    No, you never created an array; only declared it. You never dimensioned it. – rory.ap Dec 14 '15 at 22:01
  • take a look at the above example of my code – charlie Dec 14 '15 at 22:01
  • 1
    Yes, I'm looking at it. It's got `Dim BoldRows() as String` but that's only a declaration. You're just telling the code what types the array is going to hold. You never create the array giving the number of elements it's going to hold. You can do that in a few ways, e.g. by changing your declaration like this: `Dim BoldRows(30) as String` – rory.ap Dec 14 '15 at 22:04
  • 1
    I'd suggest you google arrays in VB.net – rory.ap Dec 14 '15 at 22:05
  • 1
    I made a quick [.NET Fiddle](https://dotnetfiddle.net/CYOMfI) page for some examples, look at them and see what questions you might still have. – AWinkle Dec 14 '15 at 22:19
  • the problem is, i dont know how many elements the array is going to hold – charlie Dec 14 '15 at 23:10
  • Possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – David Wilson Dec 17 '15 at 13:18

2 Answers2

4

Because of

the problem is, i don't know how many elements the array is going to hold

Use List(Of T), From MSDN
Lists are exactly a type of collection which you can use when you don't know a number of items you will put in there.
Then your code will look like

'Integer because you assign Integer value in the List
Dim BoldRows As New List(Of Integer)()

Dim detail_table_row as Integer = 1
While reader.read
    detail_table_row = detail_table_row + 1
    BoldRows.Add(detail_table_row)
End While

For Each row As Integer In BoldRows
    oDoc_detail_table.Range.Rows(row).Range.Font.Bold = True
Next

Arrays are still good in the cases where you know a number of the items.

Fabio
  • 28,602
  • 3
  • 26
  • 58
0

try this :

Dim detail_table_row as Integer = 0
While reader.read
    **ReDim preserve BoldRows(detail_table_row)**
    BoldRows(detail_table_row) = detail_table_row
    detail_table_row = detail_table_row + 1
End While
Matteo Z
  • 1
  • 1