【问题标题】:Getting value from combobox and send it as a parameter to a method从组合框中获取值并将其作为参数发送给方法
【发布时间】:2017-07-09 09:47:46
【问题描述】:

我的 WinForms 中有一个组合框,它的值从 1 到 5。我想知道如何将选定的组合框值作为参数发送给方法。

我正在使用以下代码填充我的组合框。

public class Form
{
    public Form()
    {
        this.InitializeComponent();
        const int maximumValue = 5;
        for (var i = 1; i <= maximumValue; i++)
        {
            this.comboBox1.Items.Add(i);
        }

        this.comboBox1.SelectedIndex = 4;
    }
}

我想使用上面的组合框选择作为参数,而不是向下面的函数声明int maxValue = 5 变量

private class Test
{
    private bool Check(int number, int maxValue = 7)
    {
       // Some logic here where I can use comboBox value;
    }

    // Test is an Enum
    public static Test Differentiate(string file1, string file2)
    {
       bool equal = true;
       var number = 1; 

       // Some logic here;

      // currently I am just passing number as a parameter
      equal = Check(number);

      return Test.Ok;
    }
}

另外,一个类中的comboBox 代码和我想使用comboBox.SelectedItem 值的方法在另一个类中。如何在我想使用的类中调用comboBox 代码?

任何人都可以就如何实现这一目标给我任何建议吗?

【问题讨论】:

  • 您可以使用combobox1.SelectedValue获取选定的值并将其转换为int并传递给方法。
  • @ChetanRanpariya 谢谢你的建议 :) 另外,我还有一个问题。我在一个类中有comboBox 代码,而我想使用comboBox.SelectedItem 值的方法在另一个类中。如何在我想使用的类中调用comboBox 代码?
  • 你没有在那个类中使用组合框。您将组合框的值作为参数传递给方法。您需要将方法设为公开而不是私有。如果您可以共享更多代码,例如您从哪里调用检查方法,将更容易提供更好的解决方案。
  • @ChetanRanpariya 我已经编辑了我的问题并提供了更多信息,你能看看吗?谢谢你:)
  • 您应该在Differentiate 方法中再添加一个参数maxValue 并将其传递给Test 方法,因为equal = Check(number, maxCalue); 为什么您有一个静态方法和一个非静态方法?你怎么在表单中调用Differentiate

标签: c# .net winforms combobox


【解决方案1】:
public object GetComboBoxItem(int index)
{
    if (index >= MyCombo.Items.Count)
        return null;

    return MyCombo.Items[index];
}

因此,您将返回该值并在另一个子例程中使用它

【讨论】:

    猜你喜欢
    • 2018-07-11
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-18
    • 1970-01-01
    相关资源
    最近更新 更多