0

I'm trying to dynamically create variables if possible.

I have a list box containing check boxes. The user selects items from it and the selections are then added to a database. They can select any number of items from the list (1-7). I have iterated through the selected items and added them to an arraylist.

I now want to store each selected item in a different variable to be added to the database. The idea is to use just one insert statement which is expecting 7 entries. If the user only selects say 2 items, these are inserted as well as 5 empty strings.

    Dim part1 As String = ""
    Dim part2 As String = ""
    Dim part3 As String = ""
    Dim part4 As String = ""
    Dim part5 As String = ""
    Dim part6 As String = ""
    Dim part7 As String = ""

    'add selected items to an array
    For i = 0 To listPart.CheckedItems.Count - 1
        selected.Add(listPart.CheckedItems(i).Text)
    Next

I'd like to do something like:

    For j = 0 To selected.Count
        part+j = selected(j)
    Next

This way I should have variables holding empty strings if the user does not select all 7 items

4

2 に答える 2

2

I don't think dynamic variables can be created, or need to be created.

Objects like ArrayList, Array, List, and Collection support adding items ( similar to how you are describing adding dynamic variables)

If you are looking to add a database entry for each item in the listview it's possible you could just loop through the listview

 For item as ListViewItem in listPart.Items
     'Save item.Text
 Next item
于 2012-12-05T16:40:04.033 に答える
1

you can do this with reflection, but it is not advisable. It is hard to debug, it is hard to implement, and it can lead to issues down the road with access restrictions.

http://msdn.microsoft.com/en-us/library/6z33zd7h.aspx

System.Reflection.FieldInfo FI = T.GetField("part" & j);
FI.SetValue({your class name here},selected(j));
于 2012-12-05T16:40:51.860 に答える