简体   繁体   中英

ComboBox SelectedValue Returning an Object And Not The Value

Goal: When my form loads I am doing a database call which is returning to me a DataTable that I want to assign as a KeyValuePair(string,string) as the datasource to a combo-box. With the Display Member being the key (RailCarID) and the Value Member being the value (RailcarTransaction_Guid)(I am storing it as a string).

The problem I am having, is when I do combobox.SelectedValue...It is returning to me an object rather than a string. Can anyone suggest what I am doing wrong here?

I was originally using a dictionary (and it would error out), and thru searching to resolve my issue ended up using a BindingList. Now my combobox on my application displays the object array in the display. Below, is some code snippets:

    private void GetAllTransactions()
    {
        BindingList<KeyValuePair<string, string>> Transactions = new BindingList<KeyValuePair<string, string>>();
        string sql = "SELECT * FROM RailcarTransaction WHERE IsComplete = 'True' AND IsUploaded = 'False'";
        DataTable transactions = session1.GetRecords(sql);
        for (int i = 0; i < transactions.Rows.Count; i++)
        {
            Transactions.Add(new KeyValuePair<string, string>(transactions.Rows[i]["RailCarID"].ToString(), transactions.Rows[i]["RailcarTransaction_Guid"].ToString()));
        }       
        cboxRailCars.DisplayMember = "Key";
        cboxRailCars.ValueMember = "Value";
        cboxRailCars.DataSource = Transactions;
    }

Since ComboBox.ValueMember could be set to a property of any data type (it could be an int or DateTime for example, not necessarily a string ), the SelectedValue property is an object.

You have to know what type you're actually dealing with and convert it back:

var selectedRailCar = Convert.ToString(cboxRailCars.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