簡體   English   中英

將數據綁定DataGridView上的單元格類型更改為自定義DataGridViewCell類型

[英]Change Cell Type on Databound DataGridView to Custom DataGridViewCell Type

我正在使用本文中的代碼創建一個DataGridViewProgressCell,它采用0到100之間的整數,並將該值顯示為百分比以及與DataGridView單元格中的進度條類似的圖像。

當我不使用數據綁定的DataGridView時,這很好用,但是當我將數據綁定到具有整數屬性的對象列表時,我不知道如何告訴DataGridView特定的列應被視為新的DataGridViewProgressCell類型。

在下面的代碼中,百分比是Car對象上的integer屬性。 我得到的錯誤是運行時錯誤:

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

默認情況下,DGV自動填充列。 如果要使用自定義列,則需要手動填充列。 首先設置DataGridView.AutoGenerateColumns = false ,然后添加所需的列,而不是嘗試更改現有(自動填充)列的模板。

如果我正確理解了您的問題,這就是我的答案。 我有一個datetimepickercolumn,我把它作為CellTemplate並確定。

添加列時,我將datetimepickercolumn指定為Templete。

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

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM