2010-10-29 38 views
1

我使用在this article代码来创建一个DataGridViewProgressCell这需要在0和100之间的整数,并显示该值作为百分比连同看起来像一个进度条的图像在DataGridView单元格中。更改细胞类型自定义的DataGridViewCell类型

这工作正常,当我没有使用数据绑定DataGridView,但是当我绑定到具有整数属性的对象列表,我无法弄清楚如何告诉DataGridView特定列应被视为新的DataGridViewProgressCell类型。

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

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(); 
     } 
    } 
} 

回答

2

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

+0

因此,设置的AutoGenerateColumns为false,手动定义列,然后设置数据源到绑定列表,对不对?以该顺序? – Dave 2010-10-29 13:59:00

+0

唯一重要的顺序是你设置DataSource属性之前,但它似乎合乎逻辑添加数据之前添加列的AutoGenerateColumns一定是假的。 – Tergiver 2010-10-29 14:02:11

2

如果我正确理解你的问题,这里就是我的回答。我有一个datetimepickercolumn,我把它作为CellTemplate并确定。

当我添加列时,我将它作为模板我的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) { } 
} 

希望这会有所帮助。

+0

谢谢你的男人!我花了2个小时寻找这个解决方案 – Flux 2016-06-06 03:30:33