在列表控件中插入KeyValuePair<string,string>的值时,如何停止出现[ ]?

问题描述 投票:0回答:3

就目前而言,我使用一个字典来存储问题的答案,格式如下:-。

Destination:
A1 - Warehouse
A2 - Front Office
A3 - Developer Office
A4 - Admin Office
B1 - Support

A1、A2等是用来选择其他地方问题的唯一标识符,答案在最后被标记上,字典存储ID和答案。

这一部分都能正常工作。问题是当把数据插入到一个列表框combo box中时。目前我使用的是下面的方法。

foreach (KeyValuePair<string, string> oTemp in aoObjectArray)
{
    if (listControl is ComboBox)
    {
        ((ComboBox)listControl).Items.Add(string.Format("{0} - {1}", 
                                          oTemp.Key, oTemp.Value));
    }
    else if (listControl is ListBox)
    {
        ((ListBox)listControl).Items.Add(string.Format("{0} - {1}",
                                         oTemp.Key, oTemp.Value));
    }
}

这样可以将正确的数据插入到列表框中 但格式如下:

Destination:
[A1: Warehouse]
[A2: Front Office]
[A3: Developer Office]
[A4: Admin Office]
[B1: Support]

我试过很多其他方法来消除方括号。有趣的是,如果我只是做

((ComboBox)listControl).Items.Add(string.Format(oTemp.Value));

我还是以[A1:仓库]的格式把数据拿出来。如何才能去掉方括号?

EDIT:被要求添加更多的代码。下面是完整的添加到列表控制方法。

public static void AddDictionaryToListControl(ListControl listControl,
                              Dictionary<string, string> aoObjectArray)
    {
        foreach (KeyValuePair<string, string> oTemp in aoObjectArray)
        {
            if (listControl is ComboBox)
            {
                ((ComboBox)listControl).Items.Add(string.Format(oTemp.Value));
            }
            else if (listControl is ListBox)
            {
                ((ListBox)listControl).Items.Add(string.Format(oTemp.Value));
            }
        }
    }

这个方法是由..:

    public ComboBox AddQuestionsComboBox(Dictionary<string, string> Items,
                       string Label, string Key, int Order, bool Mandatory)
    {
        ComboBox output; 

        output = AddControl<ComboBox>(Label, Key, Order);
        FormsTools.AddDictionaryToListControl(output, Items);
        AddTagField(output, Tags.Mandatory, Mandatory);

        return output;
    }

用下面这行来调用

AddQuestionsComboBox(question.PickList, question.PromptTitle, question.FieldTag, 
i, offquest.Mandatory);

希望能帮到你

EDIT:我已经尝试了下面所有的建议,但仍然没有改善--我已经检查并重新检查了代码和所有与之相关的方法,以寻找我遗漏的一些额外的格式化,没有发现任何可能导致格式化在一个阶段被正确设置,然后到屏幕上的时候又被淘汰。

c# combobox listbox keyvaluepair
3个回答
1
投票

我看不出有什么问题。

var aoObjectArray = new Dictionary<string, string>();
aoObjectArray["A1"] = "Warehouse";
aoObjectArray["A2"] = "Front Office";
aoObjectArray["A3"] = "Developer Office";

foreach (KeyValuePair<string, string> oTemp in aoObjectArray)
{
    ((ComboBox)listControl).Items.Add(string.Format("{0} - {1}", oTemp.Key, oTemp.Value));
}

1
投票

这样做很傻,但可以试试把。

((ComboBox)listControl).Items.Add(string.Format("{0} - {1}", 
                                  oTemp.Key, oTemp.Value));

行与

string item = string.Format("{0} - {1}", oTemp.Key, oTemp.Value);
((ComboBox)listControl).Items.Add(item);
© www.soinside.com 2019 - 2024. All rights reserved.