简体   繁体   English

从没有ToString C#的Combobox(string)检查值

[英]Checking value from Combobox(string) without ToString C#

I'm doing a project where "ToString" is being used as a method. 我正在做一个项目,其中“ ToString”被用作方法。

private void button1_Click(object sender, EventArgs e)
{
    if(cboPlaneType.SelectedItem = "Generic")
    {
    }
    else if (cboPlaneType.SelectedIndex = "Passenger")
    {
    }
    else if (cboPlaneType.SelectedIndex = "Fighter Jet")
    {
    }
}

And in this case i'm not sure what to do. 在这种情况下,我不确定该怎么做。 As you can see I've tried a few different option but with no avail. 如您所见,我尝试了几种不同的选择,但无济于事。 I've also tried if((string)cboPlaneType.SelectedItem = "Generic") And that didn't work. 我也尝试过if((string)cboPlaneType.SelectedItem = "Generic") ,但是那没有用。

**Edit Just to point out, SelectedValue wasn't the correct answer. **编辑只是指出,SelectedValue不是正确的答案。 ended up being " if((string)combobox.SelectedItem == "Generic") 最终是“ if((string)combobox.SelectedItem == "Generic")

The equality operator in c# is == ; c#中的相等运算符为== ; = is an assignment operator. =是赋值运算符。

SelectedIndex will return an int representing the zero-based position of the item that is selected. SelectedIndex将返回一个intint表示所选项目的从零开始的位置。 (I'm guessing it returns -1 when no item is selected.) (我想如果没有选择任何项目,它将返回-1。)

SelectedItem can be an object of any type; SelectedItem可以是任何类型的对象。 if it is not a string then you can't match it by comparing with a string. 如果不是字符串,则无法通过与字符串进行比较来匹配它。

Are you saying that the objects with which the ComboBox is populated override ToString() ? 您是说用来填充ComboBox的对象覆盖ToString()吗? You should still be able to use the result of that method for comparison, because it can only return a string . 您仍然应该能够使用该方法的结果进行比较,因为它只能返回string Otherwise, you might be able to use SelectedValue , but this depends on what kind of ComboBox you are using and how you have set it up. 否则,您可能可以使用SelectedValue ,但这取决于您使用的是哪种ComboBox以及如何对其进行设置。

SelectedIndex is an property of type Int32 . SelectedIndexInt32类型的属性。 Maybe you want to use SelectedValue instead ? 也许您想使用SelectedValue代替?

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

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