0

我有一些代码将打开一个 sqllite 数据库,获取一些街道名称,并填充一个列表框,然后将其附加到一个组合框,以便它可以在用户键入名称时建议名称。我想制作一个可以调用的程序来执行此操作,因为它将用于可能不同的组合框。我可以将控件的名称传递给它,但是如何在将控件称为变量的同时修改控件的属性?

就像是:

string A = "cbSTreets"
[A].text = "Sets the Text for the combo box."

如果有人能指出我正确的方向,我将不胜感激。

4

3 回答 3

1

You could try something like this:

private void SetText(List<string> streets, ComboBox cb)
{
    cb.DataSource = streets;
}

Of course, you'll need to fill the streets from your database and pass in the ComboBox control you want to populate. You can use another collection if you like, but ComboBox datasources need to implement the IList interface.

于 2013-04-25T14:38:14.923 回答
1

与其将其作为控件的名称传递,不如直接传递控件本身(尤其是当它们都是组合框且类型相同时?)

或者,如果由于某种原因您无法传递控件本身,如果您需要使用字符串名称,则可以使用字典之类的数据结构进行设置:

Dictionary<string, ComboBox> comboBoxes = new Dictionary<string, ComboBox>();

//Use the string you want to refer to the combobox and the combobox item itself
comboBoxes.Add("bcbsTreets", comboBox1); 

//Use the name as defined in the previous step to get the reference to the combobox and
//set the text
comboBoxes["bcbsTreets"].Text = "whatever";
于 2013-04-25T14:37:26.233 回答
0

This is only possible via reflection and should be avoided!

You should do this the normal way.

For the solution how to do it with reflection, look here: How to access class member by string in C#?

于 2013-04-25T14:38:49.460 回答