开发者

How to (or can I) list attributes of objects from a Generic list, displaying it in a combobox

I'm just a beginner, so I think I'll run into such problem very often.

Here is the thing.

I have a generic list of objects, let's say garage, many Car objects are in the garage.

List<Cars> garage=new List<Car>();

Car has attribute, like car.make; car.model; car.year;

Now I have this garage list, and several car has been added to this list.

what I want to do is to using a ComboBox to list one specific attribute of these cars.

for example I want to have this dropdown list displaying the car's year (assume all cars have distinct year). All I can go so far is like this, but don't know how to go further.

    myComboBox.DataSource = garage???

Could anyone help me point out something? I know it should has something to do with Generic List, but the books I have use only couple pages on this and not go into it further.

    namespace test
    {
        public partial class Form1 : Form
        {
            List<car> garage = new List<car>();
            public Form1()
            {
                InitializeComponent();
                car c1 = new car(98, "corolla", "toyota");
                car c2 = new car(99, "camary", "toyota");
                car c3 = new car(00, "eclipse", "misubishi");

                garage.Add(c1);
                garage.Add(c2);
                garage.Add(c3);
                foreach (car c in garage)
                开发者_C百科{
                    cBox.Items.Add(c.make);
                }
            }



            private void button1_Click(object sender, EventArgs e)
            {
                MessageBox.Show(garage[cBox.SelectedIndex].make);
            }
        }
        class car 
        {
            public int year;
            public string make;
            public string brand;
            public car(int y, string m, string b)
            {
                year = y;
                make = m;
                brand = b;
            }
        }
    }


I don't know which combo You use (Winforms, WebForms) but there should DisplayMember (what attribute will be used as text in combo) and ValueMember (which attribute will be used as value)

http://windowsclient.net/blogs/faqs/archive/2006/07/12/what-are-the-displaymember-and-valuemember.aspx


You can have following

    myComboBox.DisplayMember = "year";//Here year is the car year
    myComboBox.ValueMember = "name";//Here name is the car name
    myComboBox.DataSource = garage;

Thanks Ashwani


Now I have a solution, is to use iterator to add items.

foreach (car c in garage)
        {
            cBox1.Items.Add(c.make);
            cBox2.Items.Add(c.year);
        }

this will work good enough.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜