简体   繁体   中英

How to run a string as a command in Visual Basic (VB.NET)

i am running a Sub which takes as arguments a Datatable and a String.

Private Sub Populate(ByVal dttemp As DataTable, ByVal strWhichPart As String)

At one point there is a combobox which is populated with some of the data in the datatable. The name of the combobox is cmd plus the name of the string for example when the string is Person_FirstName the name of the combobox is cmbPerson_FirstName. Then i add items to the combobox like this:

 cmbPerson_FirstName.Items.Add(strHold(rr))

My question is this can i make a String into a command? Because i have many comboboxes which have the same name as the string argument of the sub how can i do something like this to work

strWhichPart.Items.Add(strHold(rr))

in which strWhichPart is a string. Is there a command that i can execute a string as a command? Thank you.

如果我理解正确,只需使用字符串作为键从Form的Controls集合中获取正确的Controls

CType(Controls(strWhichPart), ComboBox).Items.Add(strHold(rr))

You can use reflection to achieve this by creating an assembly with the code in a method, but its really not recommended. As in, it's insane. I suspect there are no problems in .NET development that need this approach.

Rather than using this approach, actually pass the relevant combo box as an argument - not an arbitrary string. Combo boxes are objects like anything else. You could create a dictionary which allows you to lookup combo boxes by a string. Something like:

Dictionary(Of String, ComboBox) MyDictionary = new Dictionary(Of String, ComboBox)()
MyDictionary.Add("ComboBoxA", objComboBoxA)
ComboBox objTheComboBox = MyDictionary("ComboBoxA")

The name you give your objects should not be semantically relevant in your code. If I name an object "lstMyObjectNamedThisWayForAReason1" I should NOT be using that to reference it. Instead, there should be a separation between what constitutes a GUI element and how it is referenced.

For example, if I create a WinForms GUI and reference all the items directly, then later have to write another front-end using a different framework I have to rewrite every reference. This isn't a problem if you don't tie your logic directly into your controls.

The only reason to tie them together is laziness and lack of respect for co-workers who might have to improve on your code in future. Why should they care what the GUI looks like? They might not even be using Visual Studio! They certainly can't take your code and use it elsewhere without ripping out your GUI dependency.

With a minor modification of ho1 it worked. Thanks a lot

 CType(Controls("cmb" + strWhichPart), ComboBox).Items.Add(strHold(rr))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM