简体   繁体   中英

C# Convert String from Combo Box to Int and pass it

I have declared a variable "string text"

In another fnction I take the value from a ComboBox with a function:

comboBox1.Text = gUI.getText();

and

public string getText()
    {
        return text;

    }

and pass the value text as parameter to a program.

How can I change the text in the ComboBox to Integers? There are two states that you can choose from: "Yes" and "No". I want to pass the "Yes" as 1 and the "No" as 0 to the program. How to manage that?

You want to return an int depending on what item is selected in your ComboBox? Have you tried the SelectedIndex property:

public int GetText()
{
    return comboBox1.SelectedIndex;
}

If your ComboBox has the items No , Yes , and Maybe , then if you select No result will be 0 , if you select Yes result will be 1 , if you select Maybe result will be 2 , etc.

Well , not clear but I suspect you want something like this;

public int getText(string str)
{
    if(str == "Yes")
      return 1;
    if(str == "No")
      return 0;
    return -1;
}

.Text property of your ComboBox requires string type, that's why you need to use string representations of these integers like (or use .ToString() method);

comboBox1.Text = gUI.getText().ToString();

No I want to catch the string from the ComboBox and if it is "Yes" then save the value 1 and pass this as parameter to the program. Same with "No"

If I understand correctly, you wanna check the text of comboBox1 like;

public int getText()
{
    if(comboBox1.Text == "Yes")
       return 1;
    if(comboBox1.Text == "No")
       return 0;
    return -1;
}

But save these value to where and pass this as parameter to the which program?

If you still wanna return strings, you can use like;

public string getText()
{
    if(comboBox1.Text == "Yes")
       return "1";
    if(comboBox1.Text == "No")
       return "0";
    return "-1";
}

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