views:

24

answers:

1

I'm using the code in this article to create a DataGridViewProgressCell which takes an integer between 0 and 100 and displays the value as a percent along with an image that looks like a progress bar in a DataGridView cell.

This works fine when I'm not using a databound DataGridView, but when I databind to a list of objects with an integer property, I can't figure out how to tell the DataGridView that the particular column should be treated as the new DataGridViewProgressCell type.

In the code below Percent is the integer property on a Car object. The error I'm getting is a run time error:

Value provided for CellTemplate must be of type System.Windows.Forms.DataGridViewTextBoxCell or derive from it.

Here's the code:

namespace GridViewSample
{
   public partial class Form1 : Form
   {
       private SortableBindingList<Car> carlist = new SortableBindingList<Car>();

       public Form1()
       {
          InitializeComponent();

          // databind the datagridview to the car list
          dataGridView1.DataSource = carlist;

          DataGridViewCell cell = new DataGridViewProgressCell();

          // run time error occurs on this line
          dataGridView1.Columns["Percent"].CellTemplate = new DataGridViewProgressCell();
       }
   }
}
+1  A: 

By default the DGV populates columns automatically. If you want to use custom columns you need to populate the columns manually. First set DataGridView.AutoGenerateColumns = false, then add the columns you need, rather than trying to alter the template of an existing (auto-populated) column.

Tergiver
So, set AutoGenerateColumns to false, manually define the columns, then set DataSource to the binding list, right? In that order?
Dave
The only order that matters is that AutoGenerateColumns must be false before you set the DataSource property, though it seems only logical to add the columns before adding the data.
Tergiver