PWilliams0530
PWilliams0530

Reputation: 170

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

Upvotes: 0

Views: 3682

Answers (1)

Grant Winney
Grant Winney

Reputation: 66439

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

Upvotes: 1

Related Questions