我正在使用this article中的代码创建一个DataGridViewProgressCell,它接受0到100之间的整数,并以百分比形式显示该值,同时显示一个看起来像DataGridView单元格中的进度条的图像。 / p>
当我没有使用数据绑定DataGridView时这很好用,但是当我将数据绑定到具有整数属性的对象列表时,我无法弄清楚如何告诉DataGridView特定列应该被视为新的DataGridViewProgressCell类型。
在下面的代码中,Percent是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();
}
}
}
答案 0 :(得分:2)
默认情况下,DGV会自动填充列。如果要使用自定义列,则需要手动填充列。首先设置DataGridView.AutoGenerateColumns = false
,然后添加所需的列,而不是尝试更改现有(自动填充的)列的模板。
答案 1 :(得分:2)
如果我理解你的问题,这是我的答案。我有一个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) { }
}
希望这有帮助。