简体   繁体   中英

How to get Combobox value from form to class?

Today I started a C# project and I have one problem, I have Form1.cs and Class1.cs, my form1 has a Combobox1 .

So I tried this in my class form:

If (Form1.ComboBox1.SelectedItem = "Something") 
{
    //do something 
}

But I get errors, I don't know what to do?

This should do it.

If (ComboBox1.SelectedText == "Something") 
{
    //do something 
}

also, for posterity

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.)

And it's probably also important to note the differences between = and == .

// set a variable to something
var something = "something";

// compare two values
if(val1 == val2){
    // do something
}

Based on your answer to Chase, you probably need to add class1.cs as a reference to the project form1.cs is in. Assuming you are using VS, right click on the project name in Solution Explorer, select Add Reference, select the bottom option on the left (I think it's solution, but I don't have VS in front of me) and select the project class1.cs is in. Then make sure that you add class1.cs' namespace in your usings.

For more information, look here: http://msdn.microsoft.com/en-us/library/7314433t%28v=vs.90%29.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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