0

请问这里有什么问题

abc = labGuns.Text;  // multiline label
string[] arr = Regex.Split(abc, "\r\n");
x = 0; 
foreach (string line in arr)
{
    MessageBox.Show(line); //works fine - shows each line of label
    x = x + 1;
    string abc = "cbGuns" + x.ToString();
    MessageBox.Show(abc); //works fine - shows "cbGuns1", "cbGuns2"...
    foreach (Control c in panPrev.Controls)
    {
        if (c.Name == abc) // five combos named cbGuns1, cbGuns2...
        {
            c.Text = line; //doesn't work. No combo changes its text
        }
    }
}

如果我将最后一行更改为 - c.Text = "323"- 也没有发生任何事情。
因此,错误显然在代码末尾附近。

此代码也有效(作为测试):

foreach (Control c in panPrev.Controls)
{
if (c.Name == "cbGuns1")
{
c.Text = "323";
}
}
4

4 回答 4

2

如果您的控件是组合并且您想要设置“文本”属性而不具有项目列表,那么您的组合应该具有DropDownStyle = DropDown

于 2012-06-28T14:48:32.347 回答
1

尝试将 c 转换为 DropDownList

DropDownList ddl =(DropDownList) c;<br/>
ddl.Text ="your text"
于 2012-06-28T14:43:45.870 回答
1

如果我对您的理解正确,您想在 Combobox 中添加一行,而不是选择当前其中的一行,对吗?为此,您不要将 Combobox 的 Text 值设置为字符串,您需要向 Combobox 添加一个新的 ComboboxItem,如下所示:

c.Items.Add(line);

代替

c.Text = line;

让我知道这个是否奏效!

编辑:好的,因为您正在尝试更改组合框的选定项目,所以我只想写

c.SelectedItem = line;
于 2012-06-28T14:45:51.000 回答
1

尝试替换c.Text = line;c.Items.Add(line);.

AddRange但是,在添加多个项目时是首选,因此请尝试以下操作,而不是foreach循环:

foreach (Control c in panPrev.Controls)
{
    if (c.Name.StartsWith("cbGuns"))
    {
        c.Items.AddRange(arr);
    }
}
于 2012-06-28T14:48:18.367 回答