简体   繁体   English

ComboBox的SelectedIndex始终为-1

[英]SelectedIndex of a ComboBox is always -1

I have a method creating a ComboBox, and on SelectedIndexChanged I need the text so I could use another method, but the SelectedIndex is always -1, no matter what is chosen. 我有一个创建ComboBox的方法,在SelectedIndexChanged上我需要文本,以便可以使用另一种方法,但是无论选择什么,SelectedIndex始终为-1。 I am new to C# so I really do not understand what the problem could be. 我是C#的新手,所以我真的不明白问题可能是什么。

This is the method where the ComboBox is created: 这是创建ComboBox的方法:

public ComboBox GetSize(string uri) {
   xmlReader = GetXmlReader(uri + "/People");
   ComboBox cb = new ComboBox();
   while (xmlReader.ReadToFollowing("site")) {
       cb.Items.Add(xmlReader.GetAttribute(0));
   }
   return cb;
}

This is where it is added to a TabControl: 这是将其添加到TabControl的位置:

cb = esrl.GetSize(uri);
cb.SelectedIndexChanged += new System.EventHandler(cb_SelectedIndexChanged);
page.Controls.Add(cb);

And this is where I try to get the information about the SelectedItem text, but the Index is always -1. 这是我尝试获取有关SelectedItem文本的信息的地方,但是索引始终为-1。

private void cb_SelectedIndexChanged(object sender, EventArgs e) {
    string attribute = cb.Items[cb.SelectedIndex].ToString();
    MessageBox.Show( " " + attribute);
}

It's because "cb" is not recognized as this particular ComboBox. 这是因为“ cb”未被识别为特定的ComboBox。 Try to declare 尝试声明

ComboBox cb = new ComboBox();

as a field for the whole class. 作为整个班级的领域。

Try: 尝试:

private void cb_SelectedIndexChanged(object sender, EventArgs e) {
    ComboBox c = sender as ComboBox;
    if(c == null) return;

    string attribute = c.Items[c.SelectedIndex].ToString();
    MessageBox.Show( " " + attribute);
}

This will make sure you are accessing the same combo box for which the event got fired. 这将确保您访问的事件已触发了相同的组合框。

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

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