C# ComboBox-如何将ComboBox中项目的值传递给我的属性?

C# ComboBox-如何将ComboBox中项目的值传递给我的属性?,c#,combobox,C#,Combobox,我有一个财产: public override int Length { get { return _length; } set { if (value > MaxLength) throw new ArgumentException( "Canoes are limited to 21 feet long!");

我有一个财产:

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

使用
SelectedValue
代替
SelectedIndex

Length = Convert.ToInt32(cboLength.SelectedValue);

由于
SelectedValue
可能包含任何数据类型,因此它是一个
对象
。您需要将其转换回存储在其中的数据类型,在本例中为
int

我通常使用.SelectedIndex从items集合中获取文本对象,获取.text值并解析它

int.Parse(cboLength.Item[cboLength.SelectedIndex].Text);
//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,

如果已将
ValueMember
属性设置为组合框,并且值
14,17,21
存储为数据成员。然后可以使用
SelectedValue
属性。但是,如果您没有将这些值绑定为combobox的数据成员,则必须使用combobox的
.Text
属性

例如,如果您像这样绑定组合框

cmb.DisplayMember = "Length";
cmb.ValueMember = "Length"; //To use the SelectedValue property you must have assigned this property first.
cmb.DataSource = dbSource;
cmb.Items.Add(14);
cmb.Items.Add(17);
cmb.Items.Add(21);
然后你可以得到这样的值

Length = Convert.ToInt32(cboLength.SelectedValue),
但是,如果您没有指定ValueMember属性或手动填充组合框,则在这种情况下,您不能使用
SelectedValue
属性

//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,
如果您正在手动填充组合框。像这样

cmb.DisplayMember = "Length";
cmb.ValueMember = "Length"; //To use the SelectedValue property you must have assigned this property first.
cmb.DataSource = dbSource;
cmb.Items.Add(14);
cmb.Items.Add(17);
cmb.Items.Add(21);

然后,您可以同时使用属性
.Text
.SelectedItem

我尝试过,但是无论我选择哪个值,本地窗口中显示的值都是0。使用cboLength.Text效果非常好,谢谢。您能告诉我有关使用ValueMember和DisplayMember属性的更多信息吗?每一个都有什么?很好。谢谢你的教育补助金!