Friday, March 16, 2012

Populating a list box from a loop

I was wondering how you would populate a listbox in asp.net with values from an array created by a loop.
here is the loop structure I am using:
Public Sub Page_Load()
Dim MyString, MyArray, Msg
Dim i as integer
Dim AddThis as string

MyString=BillDS.FieldValue("Week Reason 1", nothing)
MyArray=Split(MyString, "F", -1, vbTextCompare)

Msg=MyArray(0)

For i = 1 To UBound(MyArray)
Msg=Msg & "," & MyArray(i)
Next
lblReasonforError.Text=Msg

End Sub

I can get it to populate the first value in the array but I need it to populate all the values in the array which will vary according to the record it is looking at. Then with those value(s) I want to populate a listbox with all the error codes that are stored in a table on sql server according to the results of the split.
For example:
tblErrorCodes
Code ErrorMessage
1 Wrong
2 Bad

Split gets the value of 1 and 2
Populate listbox like so:
Wrong
Bad
Hope this is clear
Thank you

You can simply bind datalist to an array by setting the array as the datasource of the datalist
http://aspnet.4guysfromrolla.com/articles/082504-1.aspx
Hope that helps


uncleb wrote:

You can simply bind datalist to an array by setting the array as the datasource of the datalist


It's the simplest and the only way since ListBox doesn't have Add method.
Madmaxrtw,I'm not sure what your code is about.
But in case you need to use just some items you'd have to transform array into another one.
Or might be use DataTextField and DataValueField properties.

Hey guys I got it here is the loop script

<script language="VB" runat="server">
Public Sub Page_Load()
Dim MyString, MyArray, Msg
Dim i as integer
Dim AddThis as string


MyString=BillDS.FieldValue("Week Reason 1", nothing)
MyArray=Split(MyString, "F", -1, vbTextCompare)

Msg=MyArray(0)


For i = 1 To UBound(MyArray)
Msg=Msg & "," & MyArray(i)
Next

dlErrorList.DataSource=MyArray
dlErrorList.DataBind()

End Sub
</script>

And the DataList:
<asp:datalist CellPadding="10" ID="dlErrorList" RepeatColumns="0"
RepeatDirection="Vertical" runat="server" gridline="Both">
<ItemTemplate>
<b><%# Container.DataItem %></b>
</ItemTemplate>
</asp:datalist>

Thank you so MUCH!!!


Yakov72 wrote:

It's the simplest and the only way since ListBox doesn't have Add method.



Yes it does.
You add to the ListBox Items array. Not directly to the ListBox.

BobT wrote:


Yes it does.
You add to the ListBox Items array. Not directly to the ListBox.


You're right.
Thank you for corrections.

0 comments:

Post a Comment