views:

230

answers:

2

All,

I have a simple windows form with a combobox and a 'OK' button. After clicking the 'OK' button, I want to retrieve the selected combobox value.

The GetUserForm has 2 controls: combobox named cmbUser, with a list of 2 values button named btnOK

Nothing has been done to the GetUserForm class itself. The class contains:

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

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

Do I need to initialize something in the class? Or can I access the controls on the form using the 'f' variable above?

+1  A: 

Create an extra (public) property on your 'GetUserForm' class which returns the value of the selected item of the combobox that is on that form.

For example:

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; 
        }
    }
}

Then, you can do this:

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

          if( result != null )
              Console.WriteLine (result);
     }
}
Frederik Gheysels
This also helped me a lot in understanding the public properties.
Edward Leno
+2  A: 

You need to expose the value of the ComboBox as a public property. Something like that :

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

Or perhaps :

public int SelectedUserId
{
    get { return  (int)cmbUser.SelectedValue; }
}
Thomas Levesque
Thomas, thank you, this seemed to do the trick.
Edward Leno