简体   繁体   English

C#将字符串从组合框转换为Int并将其传递

[英]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: 在另一个函数中,我使用一个函数从ComboBox中获取值:

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? 如何将ComboBox中的文本更改为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. 我想将“是”设置为1,将“否”设置为0传递给程序。 How to manage that? 如何处理?

You want to return an int depending on what item is selected in your ComboBox? 您要返回一个整数,具体取决于您在ComboBox中选择了什么项目? Have you tried the SelectedIndex property: 您是否尝试过SelectedIndex属性:

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. 如果您的ComboBox包含项目NoYesMaybe ,则选择No结果将为0 ,如果选择Yes结果将为1 ,如果选择Maybe结果将为2 ,等等。

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); ComboBox .Text属性需要string类型,这就是为什么您需要使用这些整数的字符串表示形式的原因(或使用.ToString()方法);

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. 否,我想从ComboBox中捕获字符串,如果为“是”,则保存值1并将其作为参数传递给程序。 Same with "No" 与“否”相同

If I understand correctly, you wanna check the text of comboBox1 like; 如果我理解正确,您想检查comboBox1的文本,例如:

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; 如果您仍然想返回字符串,可以使用like;

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

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

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