views:

33

answers:

2

Why, this code create 2 the same columns in grid (Color and Color). How to inputs data color from collection in column which existing before set datasource ??

public Form1()
        {
            InitializeComponent();
            DataGridViewTextBoxColumn ds = new DataGridViewTextBoxColumn();
            ds.Name = "Color";
            dataGridView1.Columns.Add(ds);

            List<Car>  cars=new List<Car>();
            for (int i = 0; i < 5; i++)
            {
                Car car=new Car {Type = "type" + i.ToString(),Color=Color.Silver};
                cars.Add(car);

            }
            dataGridView1.DataSource = cars;


        }
A: 

You statically add a "Color" column. Then you set a List as the data source of the grid. You have a "Color" property defined in the Car class. This property is reflected and displayed as a column too.

Seb
+1  A: 

You have to set AutoGenerateColumns=false before setting the DataSource.

Take 2:

set AutoGenerateColumns=true and find the column afterward:

 var ds = dataGridView1.Columns["Color"] as DataGridViewTextBoxColumn;

That is, if you want it - your code does not really use the column so you might as well remove al the code for creating it.

Henk Holterman
It doesn't works...variables from cars dont fall in predefined columns