无法从组合框中检索数据。

时间:2011-09-15 10:11:41

标签: c# visual-studio combobox

我正在尝试显示基于在Windows窗体组合框中选择的选项的if语句的结果。 当if语句放在它自己的类中时,我遇到了问题,它与表单分开并且总是只返回else值。我把组合框公开了。 我的代码如下。

public void button1_Click(object sender, EventArgs e)
{
    xRayData xRayData1 = new xRayData();
    string shiftChangeValue;
    shiftChangeValue = xRayData1.shiftChange();
    label2.Text = shiftChangeValue;
}

public string shiftChange()
{
    frmSWChange frmSWChange1 = new frmSWChange();

    string shiftLetter;

    if (frmSWChange1.cbShift.Text == "Day")
    {
        shiftLetter = "D";
    }
    else if (frmSWChange1.cbShift.Text == "Night")
    {
        shiftLetter = "N";
    }
    else if (frmSWChange1.cbShift.Text == "Morning")
    {
        shiftLetter = "M";
    }
    else
    {
        shiftLetter = "ERROR";
    }


    return shiftLetter;
}

3 个答案:

答案 0 :(得分:1)

使用Selected...获取组合框中的所选项目

frmSWChange1.cbShift.SelectedItem // gets the binded item
frmSWChange1.cbShift.SelectedText // gets the display text of the selected item
frmSWChange1.cbShift.SelectedValue // gets the value of the selected item

答案 1 :(得分:0)

在你的方法中查看这一行

frmSWChange frmSWChange1 = new frmSWChange();

您正在创建表单的新实例,并且此实例与您所做的选择无关,这将不会在组合框中选择任何文本。您需要的是对当前正在进行这些选择的表单实例的引用。

答案 2 :(得分:0)

frmSWChange.cs

namespace X_Ray
{
public partial class frmSWChange : Form
{

    public frmSWChange()
    {
        InitializeComponent();
       frmSWChange1
    }

    private void btnReturnToMainMenu_Click(object sender, EventArgs e)
    {
        new frmMainMenu().Show();
        this.Close();
    }

    public void button1_Click(object sender, EventArgs e)
    {

        string shiftChangeValue;
        label1.Text = mtxtScrapDate.Text;
        derpderp1 = cbShift.SelectedText;
        xRayData xRayData1 = new xRayData();

        shiftChangeValue = xRayData1.shiftChange();
        label2.Text = shiftChangeValue;
    }

}
}

xRayData.cs

namespace X_Ray
{
class xRayData
{
    #region Methods


    public string shiftChange()
    {
        frmSWChange frmSWChange1 = new frmSWChange();

        string shiftLetter;

        if (frmSWChange1.cbShift.SelectedText == "Day")
        {
            shiftLetter = "D";
        }
        else if (frmSWChange1.cbShift.SelectedText == "Night")
        {
            shiftLetter = "N";
        }
        else if (frmSWChange1.cbShift.SelectedText == "Morning")
        {
            shiftLetter = "M";
        }
        else
        {
            shiftLetter = "ERROR";
        }


        return shiftLetter;
    }

    #endregion
}
}
相关问题