【问题标题】:How to retrieve combobox selection in a windows form如何在 Windows 窗体中检索组合框选择
【发布时间】:2010-05-04 09:25:08
【问题描述】:

全部,

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

GetUserForm 有 2 个控件: 名为 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”变量访问表单上的控件吗?

【问题讨论】:

    标签: c# winforms combobox


    【解决方案1】:

    您需要将 ComboBox 的值公开为公共属性。类似的东西:

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

    或许:

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

    【讨论】:

      【解决方案2】:

      在您的“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);
           }
      }
      

      【讨论】:

      • 这对我理解公共属性也有很大帮助。
      猜你喜欢
      • 2021-07-23
      • 1970-01-01
      • 1970-01-01
      • 2014-06-26
      • 1970-01-01
      • 1970-01-01
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多