C# 将数据绑定DataGridView上的单元格类型更改为自定义DataGridViewCell类型

C# 将数据绑定DataGridView上的单元格类型更改为自定义DataGridViewCell类型,c#,datagridview,C#,Datagridview,我正在使用中的代码创建一个DataGridViewProgressCell,它接受一个介于0和100之间的整数,并将该值显示为百分比以及一个看起来像DataGridView单元格中进度条的图像 当我不使用databound DataGridView时,这很好,但是当我使用integer属性将数据绑定到对象列表时,我不知道如何告诉DataGridView特定列应被视为新的DataGridViewProgressCell类型 在下面的代码中,百分比是汽车对象的整数属性。我得到的错误是运行时错误: V

我正在使用中的代码创建一个DataGridViewProgressCell,它接受一个介于0和100之间的整数,并将该值显示为百分比以及一个看起来像DataGridView单元格中进度条的图像

当我不使用databound DataGridView时,这很好,但是当我使用integer属性将数据绑定到对象列表时,我不知道如何告诉DataGridView特定列应被视为新的DataGridViewProgressCell类型

在下面的代码中,百分比是汽车对象的整数属性。我得到的错误是运行时错误:

Value provided for CellTemplate must be of type System.Windows.Forms.DataGridViewTextBoxCell or derive from it.
代码如下:

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();
       }
   }
}
名称空间GridViewSample
{
公共部分类Form1:Form
{
私有SortableBindingList carlist=新的SortableBindingList();
公共表格1()
{
初始化组件();
//数据将datagridview绑定到车辆列表
dataGridView1.DataSource=carlist;
DataGridViewCell=新DataGridViewProgressCell();
//此行出现运行时错误
dataGridView1.Columns[“Percent”].CellTemplate=new DataGridViewProgressCell();
}
}
}

默认情况下,DGV会自动填充列。如果要使用自定义列,则需要手动填充这些列。首先设置DataGridView.AutoGenerateColumns=false,然后添加所需的列,而不是试图更改现有(自动填充)列的模板。

如果我正确理解您的问题,下面是我的答案。我有一个datetimepickercolumn,我把它作为CellTemplate,ok

添加列时,我将datetimepickercolumn作为模板

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) { }
}

希望这有帮助。

所以,将AutoGenerateColumns设置为false,手动定义列,然后将DataSource设置为绑定列表,对吗?按这种顺序?唯一重要的顺序是,在设置DataSource属性之前,AutoGenerateColumns必须为false,尽管在添加数据之前添加列似乎是合乎逻辑的。