if (comboBox1.DropDownStyle == DropDownStyle.DropDown ||
comboBox1.DropDownStyle == DropDownStyle.Simple)
{
return comboBox1.Text;
}
Text
可能是最好的选择。它将当前选定的文本从 ComboBox 中作为字符串获取。
if (comboBox1.DropDownStyle == DropDownStyle.DropDownList)
{
return comboBox1.GetItemText(comboBox1.SelectedItem);
}
对于这种样式,你不能从ComboBox
中获取文本。它会返回当前SelectedIndex
所在项目的字符串。
SelectedValue(已选择的值)可能是最好的选择。
SelectedText(已选择文本)将为您提供可编辑部分的选定文本,Selected Item(已选择项)将返回对象,而selected index(已选择索引)将返回索引。通常情况下,应用程序会提取并使用SelectedValue。请查看MSDN上的ComboBox
SelectedIndex Gets or sets the index specifying the currently selected item. (Overrides ListControl.SelectedIndex.)
SelectedItem Gets or sets currently selected item in the ComboBox.
SelectedText Gets or sets the text that is selected in the editable portion of a ComboBox.
SelectedValue Gets or sets the value of the member property specified by the ValueMember property. (Inherited from ListControl.)
这取决于三件事:1. 模式 2. DropDownStyle 3. 必需值
在 ComboBox.SelectedIndexChanged 事件中
未绑定的 模式
a. DropDownStyle = DropDown
SelectedText 将返回 = SelectedText
b. DropDownStyle = DropDownList
使用数据绑定的 模式(意味着您从某个数据源,如 SQL Server 表中填充 ComboBox)。
a. DropDownStyle = DropDown
SelectedText 将返回 = SelectedText(DisplayMember 的值)
b. DropDownStyle = DropDownList
注意:您也可以使用 .Text,它将返回 ComboBox 的文本
结论:
未绑定的模式
数据绑定的模式
a. 必须使用 ValueMember
.SelectedValue 是最佳选择
b. 必须使用 DisplayMember
SelectedItem 似乎是一个安全的选择。
我有这段代码:
NRBQConsts.currentSiteNum = listBoxSitesWithFetchedData.SelectedValue.ToString();
...由于 NRE 崩溃。
将其更改为以下内容后:
NRBQConsts.currentSiteNum = listBoxSitesWithFetchedData.SelectedItem.ToString();
...它正常运行。