Friday, March 16, 2012

populating a dropdownlist with data from a multidimensional arrays

Hello,

I hope someone can help me. I have an array defined as a two dimensional array that was populated from a dataset. I want to take that array and populate a dropdownlist. The reason I created a two dimensional array was because in the first dimension I store the value of the dropdownlist and in the second dimension I store the text for the dropdownlist. The value is not just a column from the dataset but a string that is pieced together. Please take a look at the code below and tell me what I'm doing wrong. If someone can please help me. I'm really lost.


'This is were I populate the array
Dim objArray(,) As Object

ReDim objArray(intRowCnt - 1, intColCnt - 1)
i = 0
For Each dr In mDSet.Tables(0).Rows
With mDSet.Tables.Item(0).Rows(i)
If .Item("mbo_key").ToString.Length > 0 Then
objArray(i, 0) = .Item(3).ToString.Trim & "|" & .Item(4).ToString.Trim
objArray(i, 1) = .Item(1).ToString.Trim & " - " & .Item(2).ToString.Trim & " *"
Else
objArray(i, 0) = .Item("period_key").ToString
objArray(i, 1) = .Item(1).ToString.Trim & " - " & .Item(2).ToString.Trim
End If
End With
i += 1
Next

With ddlDropDownList
.DataSource = objArray
For i = 0 To intMBO
' this is were it's blowing up!!!!!
.DataValueField = CStr(objArray(i, 0))
.DataTextField = CStr(objArray(i, 1))
Next
.DataBind()
End With

Why again are you not binding it straight to the Dataset? You should be able to do this using a Dataset, even if it is a concatenation of certain columns (you may even be able to this at the DB level)

As for your problem...you may be able to fix it if instead of using a multidimensial array, use a arrayed class that you define, then you should be able to set the .datavalue/textfield to the class properties (yes use properties). It would look much cleaner too. Very simple class

Public Class Items
Public Property Text...
Public Property Value...
End Class

Hope this helps!
--Michael
I thank you for your help but I'm not sure what you mean. I created 2 Properties like you suggested but I get an error saying I can't convert an array to string when I try to assign it to the .DataValueField of the dropdownlist. Can you please show me an example because I'm really fustrated with this problem.

Also the reason I don't bind it to a dataset is because the value of an option changes depending on if a certain field is Null or not. I wasn't sure how to do this.


With selPeriod
.DataValueField = mclsMBO.marstrValue
.DataTextField = mclsMBO.marstrText
End With

I want to thank you for your help. You set a light off in my head and I ran with it. What I did was I added to Columns to the dataset and populated them with the info I needed it and then I binded those fields to the drop down list. Once again I want to say thanks.

0 comments:

Post a Comment