从winforms中的另一个类获取组合框选择索引

时间:2016-12-07 02:53:34

标签: c# winforms combobox

我有两节课。第一个类是form1,它有一个组合框和三个选项。我一直试图找到一种方法从我的其他班级中获取当前组合框选择索引,但我的所有尝试都失败了。这是我上一次尝试的一些代码。

public partial class Form1 : Form
{

form2 herochoose = new form2();

public void comboBox1_SelectedIndexChanged_2(object sender, EventArgs e)
{
    heroischosen();
}

public int heroischosen()
{
    if (comboBox1.SelectedIndex == 0)
    {
        herochoose.HeroChoosen = 0;
    }
    else if (comboBox1.SelectedIndex == 1)
    {
        herochoose.HeroChoosen = 1;
    }
    else if (comboBox1.SelectedIndex == 2)
    {
        herochoose.HeroChoosen = 2;
    }

    return herochoose.HeroChoosen;
  }

}

和表格2

public partial class form2 : Form
{
   private int _heroChoice;

   public int HeroChoosen
   {
        get { return _heroChoice; }
        set { _heroChoice = value; }
   }

   protected override void OnPaint(PaintEventArgs e)
   {
       if (_heroChoice == 0)
       {
           Console.WriteLine("herochoice1");
       }
       else if (_heroChoice == 1)
       {
           Console.WriteLine("herochoice2");                   
       }
       else if (_heroChoice == 2)
       {
           Console.WriteLine("herochoice3");   
       }
     }
  }

当form1处于活动状态时,它表明在组合框中正确选择了每个选项,但是当我启动form2时,它永远不会保持组合框选择。对不起,如果我错过了一些非常简单的事情。

感谢。

1 个答案:

答案 0 :(得分:1)

为您提供简单的修复,在Form2的构造函数中获取值,以便您可以以简单的方式使用它:

public partial class form2 : Form
{
    private int _heroChoice;

    public int HeroChoosen
    {
        get { return _heroChoice; }
        set { _heroChoice = value; }
    }
    // constructor
    public form2(int selectedItem)
    {
       HeroChoosen = selectedItem;
       // Now you can use HeroChoosen 
    }
    // Rest of codes here
}

如果是这样,调用方法将是这样的:

public void comboBox1_SelectedIndexChanged_2(object sender, EventArgs e)
{
   form2 herochoose = new form2(heroischosen()); 
   // the return value from heroischosen will be passed to the form 2
   // and are handled their in form2's constructor
   herochoose .Show();
}
相关问题