ScottT
ScottT

Reputation: 39

ComboBox - how do I pass the value of the items in the comboBox to my property?

I have a property:

public override int Length
    {
        get { return _length; }
        set
        {
            if (value > MaxLength)
                throw new ArgumentException(
                    "Canoes are limited to 21 feet long!");
            else if (value < MinLength)
                    throw new ArgumentException(
                "The shortest canoe available is 12 feet long");
            else
                _length = value;
        }

In my form I have a comboBox with the values 14, 17, 21. I want to pass those int's to my length property. How do I do that? I am using the code below, but it passes the selectedindex 0,1,2 to my property and throws the exception for MinLength. How do I pass 14, 17, 21 to Length?

Canoe c = new Canoe()
            {
                Brand = txtBrand.Text,
                Model = txtModel.Text,
                ModelYear = cboModelYear.SelectedIndex,
                Length = cboLength.SelectedIndex,
            };

            this.Tag = c;
            this.DialogResult = DialogResult.OK;

Upvotes: 0

Views: 789

Answers (3)

Shell
Shell

Reputation: 6849

If you have set the ValueMember property to the combobox and the values 14,17,21 are stored as a data member. then you can use SelectedValue property. But, if you are not binding the those values as a data member of combobox then you have to use .Text or .SelectedItem property of combobox.

For example if you are binding the combobox like this

cmb.DisplayMember = "Length";
cmb.ValueMember = "Length"; //To use the SelectedValue property you must have assigned this property first.
cmb.DataSource = dbSource;

Then you can get the value like this.

Length = Convert.ToInt32(cboLength.SelectedValue),

But, If you are not assigning ValueMember property or you are populating combobox manually then you cannot use the SelectedValue propety in this case.

//If you are populating combobox with datasource
cmb.DisplayMember = "Length";
cmb.DataSource = dbSource;

//Then you can use .Text Property to get the value
int length = 0;
if (int.TryParse(cmb.Text, out length))
    Length = length,

If you are populating combobox manually. like this

cmb.Items.Add(14);
cmb.Items.Add(17);
cmb.Items.Add(21);

Then you can use both property .Text and .SelectedItem

Upvotes: 1

Cody Jones
Cody Jones

Reputation: 434

I typically use the .SelectedIndex to grab the text object from the items collection, and grab the .Text value and parse it.

int.Parse(cboLength.Item[cboLength.SelectedIndex].Text);

Upvotes: 0

Grant Winney
Grant Winney

Reputation: 66439

Use SelectedValue instead of SelectedIndex:

Length = Convert.ToInt32(cboLength.SelectedValue);

Since SelectedValue could potentially contain any data type, it's an object. You need to cast it back to the data type you stored in there, an int in this case.

Upvotes: 0

Related Questions