C# Can';t使用对象在组合框中设置SelectedValue

C# Can';t使用对象在组合框中设置SelectedValue,c#,winforms,C#,Winforms,我有以下代码: public partial class ModificarAlimento : Form { private Alimento alim; private Dictionary<string, Nutriente> nutrientes; public ModificarAlimento(Alimento a, Dictionary<string, Nutriente> nut) { Initialize

我有以下代码:

public partial class ModificarAlimento : Form
{
    private Alimento alim;
    private Dictionary<string, Nutriente> nutrientes;

    public ModificarAlimento(Alimento a, Dictionary<string, Nutriente> nut)
    {
        InitializeComponent();
        this.nutrientes = nut;
        alim = a;

        int i = 0;
        foreach (KeyValuePair<string, CantidadNutrientes> x in alim.Nutrientes) 
        {
            ComboBox n = new ComboBox();
            n.DropDownStyle = ComboBoxStyle.DropDownList;
            n.Location = new Point(12, 25 * (i + 1) + 80);
            n.DataSource = new BindingSource(nutrientes, null);
            n.DisplayMember = "Key";
            n.ValueMember = "Value";
            TextBox cNuts = new TextBox();
            cNuts.Location = new Point(150, 25 * (i + 1) + 80);
            cNuts.Size = new Size(50, cNuts.Size.Height);
            cNuts.Text = x.Value.Cantidad.ToString();
            this.Controls.Add(n);
            this.Controls.Add(cNuts);
            i++;
            n.SelectedValue = x.Value.Nutriente;
        }
    }

    private void ModificarAlimento_Load(object sender, EventArgs e)
    {

    }
}
每个
Alimento
(食品)都有一套
CantidadNutrients
(营养素)字典,其中存储一个双值和一个
Nutriente
(营养素),后者依次存储一个名称。那么,打电话

x.Value.Nutriente
将检索存储在x中的CantidadNutrients中的营养素

为什么这不起作用?感谢您的帮助

编辑:我也在尝试这个

n.SelectedIndex = n.FindStringExact(x.Key);
//and
n.SelectedValue = n.FindStringExact(x.Value.Nutriente.Nombre);
然而,由于某些奇怪的原因,它在我调试时工作,但如果我不逐行检查,它根本不工作。

您必须使用或:

注意:


可以帮助您查找与指定字符串完全匹配的项目索引。

请使用comboBox1.SelectedText,而不是此设置项目,并在组合框中显示为编辑过的文本

n.CreateControl();
在此之前。Controls.Add(),并将

n.SelectedItem = 
  n.Items
   .Cast<KeyValuePair<string, Nutriente>>()
   .SingleOrDefault(o => o.Key == x.Key);
n.SelectedItem=
n、 项目
.Cast()
.SingleOrDefault(o=>o.Key==x.Key);

调用this.Controls.Add()

我相信您的意思是
ComboBox.SelectedIndex
两种方法都不起作用。我不能设置文本(这是一个DropDownList),也不能选择索引(我正在使用字典,所以我没有关于“哪个数字”是每个条目的信息)。当我在调试时逐行检查它时,这是可行的,但如果我在不调试的情况下执行它,它就是不起作用…
n.dropdownlistle=ComboxStyle.DropDownList因此我不能。不客气,我编辑它是为了不使用Items.IndexOf,因为这样更简单。
combox.Text = "yourIetmText";
n.CreateControl();
n.SelectedItem = 
  n.Items
   .Cast<KeyValuePair<string, Nutriente>>()
   .SingleOrDefault(o => o.Key == x.Key);