views:

835

answers:

1

Hi there,

Ok, firstly I have the following code working.. although my question is this; should I code the combobox databinding like the following example, or is there an easier/more efficient way?

Firstly, I needed to manipulate the results back from the database to show a more descriptive meaning:

(I am using a basic class for the key/value pair)

class WashBayDesc
    {
        public string Key { get; set; }
        public string Text { get; set; }
    }

Now I retrieve the data from a datareader and do the manipulation I need which then adds the results to a list item:

    var washbaydata = new List<WashBayDesc>();

    //  Read through the available cashboxes and populate a list/combobox
    while (rdr.Read())
    {
        string sWashBayDesc = null;
        string sWB = rdr["washbay"].ToString();
        if (sWB.StartsWith("3"))
        {
            sWashBayDesc = "Bay " + sWB.Substring(1);
        }
        else
        {
            sWashBayDesc = "Auto " + sWB.Substring(1);
        }

        washbaydata.Add(new WashBayDesc { Key = sWB, Text = sWashBayDesc });
    }

        //  Now bind the hashtable (with our bay selectors) to the dropdown
        cmbCashBoxes.DataSource = washbaydata;
        cmbCashBoxes.ValueMember = "Key";
        cmbCashBoxes.DisplayMember = "Text";

So.. the idea is I can simply bind the ComboBox datasource to the washbaydata list object.. this works fine.

The next part is to retrieve the selected item value (i.e. not the textual description, but the value or key itself). This is the bit I think maybe doesn't quite look right, although again it works...

    WashBayDesc myRes = new WashBayDesc();
    myRes = (WashBayDesc)cmbCashBoxes.SelectedItem;
    string sWashBayCashBox = myRes.Key;

So the result is my string sWashBayCashBox has the selected key...

I guess it works, and that is fine, but is there an easier/more cleaner way?

+3  A: 
string sWashBayCashBox = (string)cmbCashBoxes.SelectedValue;
Jacob Seleznev
Thank you! excellent work. So I guess the (string) casting just gets the first element of the SelectedValue object?Either way, much much more simple and cleaner.. thank you again!
David S
I'm glad you liked it. SelectedValue returns an object that's why we need to downcast to string.
Jacob Seleznev