C# ComboBox未返回selectedItem

C# ComboBox未返回selectedItem,c#,combobox,C#,Combobox,我将数据源绑定到一个combox框,然后设置此代码 Combox1.ValueMember = "CapacityID"; Combox1.DisplayMember = "Capacitys"; 它显示数据没有问题,但当我想要获得selectedtext时,它返回了我“”并使用selectedItem返回组合框的名称! selectedvalue返回正确的数据 Combox1.SelectedItem.ToString(); //return "Combox1" Combox1.Select

我将数据源绑定到一个combox框,然后设置此代码

Combox1.ValueMember = "CapacityID";
Combox1.DisplayMember = "Capacitys";
它显示数据没有问题,但当我想要获得selectedtext时,它返回了我“”并使用selectedItem返回组合框的名称! selectedvalue返回正确的数据

Combox1.SelectedItem.ToString(); //return "Combox1"
Combox1.SelectedValue.ToString(); //Work Correctly
Combox1.SelectedText.ToString(); // return ""

Combox1.SelectedItem
retunrs您选择的ListItem对象不是所选项目的文本值

它应该是这样的:

ListItem li = Combox1.SelectedItem;

从MSDN:


Combox1.选择文本
-检查Msdn以了解以下信息:

从MSdn返回空字符串的原因-如果在按钮单击事件处理程序中检索SelectedText值,则该值将为空字符串。这是因为当输入焦点从组合框移动到按钮时,选择会自动清除

使用

Combox1.SelectedItem.Text // To get SelectedText
Combox1.SelectedItem.Value // To get SelectedValue
而不是

Combox1.SelectedItem.ToString()

所以尽管如此,你的问题并不是很清楚,要得到你所选项目的计算结果,请始终使用

Combox1.SelectedValue
为什么?

因为:

Combox1.SelectedItem
返回表示组合框中当前选定文本的字符串如果DropDownStyle设置为DropDownList,则返回值为空字符串(“”)。

ComboBox.Text.Tostring()返回所选文本并解决了我的问题

 String status = "The status of my combobox is " + comboBoxTest.Text
已从MSDN中选择文本属性

Gets or sets the text that is selected in the editable portion of a ComboBox.
Gets or sets the text associated with this control.
而MSDN中的文本属性

Gets or sets the text that is selected in the editable portion of a ComboBox.
Gets or sets the text associated with this control.

我在Combox1.SelectedItem命名空间中没有文本!为什么?“选定值起作用并返回选定值,我在选定文本中遇到问题。我不太明白您需要什么,也许您需要首先明确表示您想要什么。我的组合框有两部分,选定值和选定文本,选定值工作正常,但选定文本返回“”但我的DropDownStyle尚未设置为DropDownList,其DropDownThe类型或命名空间名称“ListItem”找不到(是否缺少using指令或程序集引用?)我在按钮单击事件处理程序中检索SelectedText值,那么解决方案是什么呢?@Moslem7026-第一个是它的对象类型或listitem,你可以从msdn文档中读取。第二个是同样的事情,你可以检查msdn,在某些情况下它会变为空白。。