C# - 从 ComboBox 对象获取 int 值 属性

C# - Getting int value from ComboBox object property

我正在使用 Windows 表单。有没有办法从 comboBox1 中当前选择的对象中获取 new_object.number_prop 值?最好不使用 comboBox1 索引。任何帮助将不胜感激。我一直在寻找解决方案一段时间了。

sampleObject new_object = new sampleObject();
new_object.text_prop = "sample text";
new_object.number_prop = 3;

comboBox1.Items.Insert(0, new_object);

class sampleObject
{
    public string text_prop {get; set; }
    public int number_prop {get; set; }
    public override string ToString();
    {
        return text_prop;
    }
}

将combobox的valueitem设为"number_prop",displayitem设为"text_prop"

你可能在说这个:

var selectedObject = (sampleObject) comboBox1.SelectedItem;
var value = selectedObject.number_prop;

另请注意,object 是 C# 中的保留字(作为 Object class 的别名)。

你的代码应该是这样的。

object new_object = new object();
new_object.text_prop = "sample text";
new_object.number_prop = 3;

comboBox1.Items.Insert(0, new_object);
comboBox1.ValueMember = "number_prop";
comboBox1.DisplayMember = "text_prop"

class SomeObject
{
    public string text_prop {get; set; }
    public int number_prop {get; set; }
    public override string ToString();
    {
        return text_prop;
    }
}