简体   繁体   English

ComboBox.SelectedValue 不起作用

[英]ComboBox.SelectedValue not working

What is wrong with this code?这段代码有什么问题?

myComboBox.Items.Clear();
myComboBox.Items.AddRange(new string[]{"one","two"});
myComboBox.SelectedValue = "one";

It is showing up with nothing selected.它显示时没有选择任何内容。

If you populate the combobox like this:如果您像这样填充组合框:

myComboBox.Items.AddRange(new string[]{"one","two"});

You must use the ComboBox.SelectedItem or the ComboBox.SelectedIndex property to set/get the selected item:您必须使用ComboBox.SelectedItemComboBox.SelectedIndex属性来设置/获取所选项目:

myComboBox.SelectedItem = "one"; //or
myComboBox.SelectedIndex = 0; 

The ComboBox.SelectedValue property is inherited from ListControl and must be used ONLY when: ComboBox.SelectedValue属性从ListControl继承,并且必须在以下情况下使用:

  • the control is bound to a DataSource控件绑定到DataSource
  • and ValueMember and DisplayMember properties are definied.并定义了ValueMemberDisplayMember属性。

A couple of different options:几个不同的选择:

1) change SelectedValue to SelectedIndex 1) 将SelectedValue更改为SelectedIndex

myComboBox.SelectedIndex = 0; //your first item

Please ignore this, this is for asp.net请忽略这一点,这是针对asp.net的

2) add in ListItem s manualy 2) ListItem添加ListItem

myComboBox.Items.Clear();
myComboBox.Items.Add(new ListItem() { Text = "one", Selected = true };
myComboBox.Items.Add(new ListItem() { Text = "two" };

Just make sure you don't have more than one item selected at a given time.只需确保您在给定时间选择的项目不超过一项。

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

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