SelectedIndexChanged无法识别动态comboBox

时间:2015-02-15 05:18:52

标签: c# combobox

我正在创建一个在运行时创建ComboBox的表单。根据ComboBox的选择,我想创建另一个适当处理用户选择的控件。在这种情况下,它是源类型的下拉列表。 在Main.Designer.cs中我有:

public System.Windows.Forms.ComboBox cboSourceTypes;

在Main.cs中我有:

namespace DataVerification
{
public partial class Main : Form
{
    public Main()
    {
        InitializeComponent();
        Iinitialize_MyForm();

    }
    public void initialize_MyForm()
    {
        ComboBox cboSourceType = new ComboBox();
        cboSourceType.Items.Add("ODBC");
        cboSourceType.Items.Add("CSV");
        cboSourceType.SelectedIndex = 0;
        tabMyFrom.TabPages[0].Controls.Add(cboSourceType);
        cboSourceType.SelectedIndexChanged += new System.EventHandler(cboSourceType_SelectedIndexChanged);           
    }

    public void cboSourceType_SelectedIndexChanged(object sender, EventArgs e)
    {           
        switch (cboSourceType.SelectedIndex)
        {
            case 1:  //ODBC - Handle this selection
                break;
            case 2:  //CSV - Handle this selection
                break;
        }
    }
}
}

当我尝试从cboSourceType内部访问cboSourceType_SelectedIndexChanged时,似乎无法访问ComboBox,即使代码与另一个未动态创建的项目中的代码相同。如何让cboSourceType_SelectedIndexChanged识别ComboBox

2 个答案:

答案 0 :(得分:2)

您在cboSourceType方法中尝试使用的cboSourceType_SelectedIndexChanged()变量是initialize_MyForm()方法的本地变量,因此超出了范围。

要获得ComboBox的有用参考,您应该将方法的sender参数转换为ComboBox

var cboSourceType = (ComboBox)sender;

执行此操作后,您应该引用触发事件的ComboBox

答案 1 :(得分:0)

问题在于您的ComboBox cboSourceType的范围。

说明:

public void initialize_MyForm()
    {
        ComboBox cboSourceType = new ComboBox(); // Where you define it
        cboSourceType.Items.Add("ODBC");
        cboSourceType.Items.Add("CSV");
        cboSourceType.SelectedIndex = 0;
        tabMyFrom.TabPages[0].Controls.Add(cboSourceType);
        cboSourceType.SelectedIndexChanged += new System.EventHandler(cboSourceType_SelectedIndexChanged);           
    }

    public void cboSourceType_SelectedIndexChanged(object sender, EventArgs e)
    {           
        // Try to access it from here : out of the scope 
        switch (cboSourceType.SelectedIndex)
        {
            case 1:  //ODBC - Handle this selection
                break;
            case 2:  //CSV - Handle this selection
                break;
        }
    }

解决方案:

从发件人那里获取所需的组合框元素,如下所示

    public void cboSourceType_SelectedIndexChanged(object sender, EventArgs e)
    {           
        switch ((ComboBox)sender.SelectedIndex)
        {
            case 1:  //ODBC - Handle this selection
                break;
            case 2:  //CSV - Handle this selection
                break;
        }
    }

有关事件处理的更多信息,请参阅this

豫ICP备18024241号-1