简体   繁体   English

C#2 ComboBox DropDownList显示相同的值

[英]C# 2 ComboBox DropDownList showing same values

In my code I have 2 ComboBox DropDownLists, created by the code below. 在我的代码中,我有2个ComboBox DropDownLists,由下面的代码创建。 The problem is that when the value of the DropDownlist get changed, the other one value also changes. 问题在于,当DropDownlist的值更改时,另一个值也会更改。 Can you please help me how I can solve this problem? 您能帮我解决这个问题吗?

public class Translate
{
    public string CountryName { get; set; }
    public string CountryCode { get; set; }
}

IList<Translate> languages = new List<Translate>();
languages.Add(new Translate("Select", ""));
languages.Add(new Translate("English", "en"));
languages.Add(new Translate("French", "fr"));
languages.Add(new Translate("Spain", "es"));

ddlFrom.DataSource = languages;
ddlFrom.DisplayMember = "CountryName";
ddlFrom.ValueMember = "CountryCode";

ddlTo.DataSource = languages;
ddlTo.DisplayMember = "CountryName";
ddlTo.ValueMember = "CountryCode"; 

That's because you're pointing both dropdown lists to the same datasource. 那是因为您要将两个下拉列表都指向同一个数据源。 You need to make a second copy of languages to pass to ddlTo.DataSource . 您需要制作第二份语言副本才能传递给ddlTo.DataSource

When you use the IList as a data source, you're implicitly synchronizing access to the list, including the notion of a 'selected' item. 当使用IList作为数据源时,您将隐式同步对列表的访问,包括“选定”项的概念。 You should be able to simply use: 您应该能够简单地使用:

        ddlFrom.Items.Clear();
        ddlTo.Items.Clear();
        foreach (var language in languages)
        {
            ddlFrom.Items.Add(language);
            ddlTo.Items.Add(language);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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