如何在Windows窗体中检索组合框选择

时间:2009-09-24 22:33:39

标签: c# winforms combobox

所有

我有一个带有组合框和“确定”按钮的简单窗体。单击“确定”按钮后,我想检索所选的组合框值。

GetUserForm有2个控件: combobox名为cmbUser,列表包含2个值 名为btnOK的按钮

GetUserForm类本身没有做任何事情。该课程包含:

public partial class GetUserForm : Form
{
    public STAMP_GetUser()
    {
        InitializeComponent();
    }
}

GetUserForm f = new GetUserForm();
f.ShowDialog();
// not sure how to access the combobox selected value?

我是否需要在课堂上初始化某些内容?或者我可以使用上面的'f'变量访问表单上的控件吗?

2 个答案:

答案 0 :(得分:2)

您需要将ComboBox的值公开为公共属性。这样的事情:

public string SelectedUserName
{
    get { return cmbUser.Text; }
}

或者也许:

public int SelectedUserId
{
    get { return  (int)cmbUser.SelectedValue; }
}

答案 1 :(得分:1)

在“GetUserForm”类上创建一个额外的(公共)属性,该属性返回该表单上组合框的所选项的值。

例如:

public class GetUserForm : Form
{
    public object SelectedComboValue
    {
        // I return type object here, since i do not know what you want to return
        get 
        {
           return MyComboBox.SelectedValue; 
        }
    }
}

然后,你可以这样做:

using( GetUserForm f = new GetUserForm() )
{
     if( f.ShowDialog() == DialogResult.OK )
     {
          object result = f.SelectedComboValue;

          if( result != null )
              Console.WriteLine (result);
     }
}
相关问题