简体   繁体   中英

access to property on selection winforms combobox

One article has Name and Price properties. I use Name property to display articles inside combobox cmbDataList like this

public Form1()
{
    InitializeComponent();
    cmbDataList.DataSource = GetData();
    cmbDataList.DisplayMember = "Name";
}

After user selected the preffered article I want to use it's Price property to assign to textbox on the same form. So, how to access to that Price property?

private void cmbDataList_SelectedIndexChanged(object sender, EventArgs e)
{
    //var sel = cmbDataList.SelectedItem;
}

You have to cast SelectedItem to proper object.

private void cmbDataList_SelectedIndexChanged(object sender, EventArgs e)
{
    var sel = (YourObject)cmbDataList.SelectedItem;
    txt.Text = sel.Price.ToString();
}

Unless all names are unique, you're going to need a unique identifier to reference, for example an articleID.

From here, set the ComboBox's ValueMember like so;

cmbDataList.ValueMember = "ID";

then you can get your value on the event handler;

private void cmbDataList_SelectedIndexChanged(object sender, EventArgs e)
{
    var sel = cmbDataList.SelectedValue;

    //From here you're going to need to find your article with that particular ID.
}

Alternatively. You could have your DisplayMember as the article name, and the price as the ValueMember , then get it in the event handler for SelectedIndexChanged in the same way i put above. SelectedValue will then return the price;

cmbDataList.ValueMember = "Price";

private void cmbDataList_SelectedIndexChanged(object sender, EventArgs e)
{
    var yourSelectedPrice = cmbDataList.SelectedValue;


}

Assuming GetData() returns a table, you need to write the ValueMember also... like this:

InitializeComponent();
    cmbDataList.DataSource = GetData();
    cmbDataList.DisplayMember = "Name";
    cmbDataList.ValueMember = "Price";

Now, your selected display will be synced with the value and you will be able to use it..

Get more info in here: Populate combobox

You Need to set ValueMember You can set in this way

cmbDataList.ValueMember = "ID";

then you write the code on cmbDataList_SelectedIndexChanged Event

May be this will help you

var sel = cmbDataList.SelectedValue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM