开发者

Change Cell Type on Databound DataGridView to Custom DataGridViewCell Type

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.F开发者_开发百科orms.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();
       }
   }
}


If I understand your question correctly, here is my answer. I have a datetimepickercolumn and i put it as CellTemplate and ok.

I asigned as templete my datetimepickercolumn when columns are added.

private void dgvFechas_ColumnAdded(object sender, DataGridViewColumnEventArgs e) {
 try {
   //Evalua si el tipo de dato es DateTime.
   if(e.Column.ValueType == typeof(DateTime)) {
        e.Column.CellTemplate = new CalendarCell();
   } 
 }
 catch(Exception ex) { }
}

Hope this helps.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜