0

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?

2 Answers 2

2

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; } } 
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

This also helped me a lot in understanding the public properties.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.