2013-03-31 78 views
3

我在搜索技巧,將用戶控件添加到datagridview單元格中,並找到下面的代碼。我只是複製粘貼代碼,但當我嘗試添加CustomColumn時,我得到錯誤。添加用戶控件

這種方式我嘗試將CustomColumn列添加到網格。

private void button1_Click(object sender, EventArgs e) 
{ 
    CustomColumn cc=new CustomColumn(); 
    dataGridView1.Columns.Add(cc); 
    dataGridView1.Rows.Add(""); 
} 

public class CustomColumn : DataGridViewColumn { 
    public CustomColumn() : base(new CustomeCell()) { } 
    public override DataGridViewCell CellTemplate 
    { 
     get 
     { 
      return base.CellTemplate; 
     } 
     set 
     { 
      // Ensure that the cell used for the template is a CalendarCell. 
      if (value != null && 
       !value.GetType().IsAssignableFrom(typeof(CustomeCell))) 
      { 
       throw new InvalidCastException("It should be a custom Cell"); 
      } 
      base.CellTemplate = value; 
     } 
    }   
} 
public class CustomeCell : DataGridViewCell 
{ 
    public CustomeCell() : base() { } 
    public override Type ValueType 
    { 
     get 
     { 
      return typeof(CustomUserControl); 
     } 
    } 
    protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) 
    { 
     CustomUserControl ctrl = (CustomUserControl)value; 
     Bitmap img = new Bitmap(cellBounds.Width, cellBounds.Height); 
     ctrl.DrawToBitmap(img, new Rectangle(0, 0, ctrl.Width, ctrl.Height)); 
     graphics.DrawImage(img, cellBounds.Location); 
    } 
    protected override void OnClick(DataGridViewCellEventArgs e) 
    { 
     List<InfoObject> objs = this.DataGridView.DataSource as List<InfoObject>; 
     if (objs != null) 
     { 
      if (e.RowIndex >= 0 && e.RowIndex < objs.Count) { 
       CustomUserControl ctrl = objs[e.RowIndex].Ctrl; 
       // Take any action - I will just change the color for now. 
       ctrl.BackColor = Color.Red; 
       ctrl.Refresh(); 
       this.DataGridView.InvalidateCell(e.ColumnIndex, e.RowIndex); 
      }  
     } 
    } 
} 

請教我如何使用上面的代碼添加自定義列。我創建了一個用戶控件,名字是CustomUserControl,但沒有運氣。謝謝

+0

你有什麼錯誤?你能過去你的錯誤嗎? –

+0

請看這個好樣本:http://social.msdn.microsoft.com/forums/en-US/winformsdatacontrols/thread/ee8eec0b-2b1a-46d2-9d2e-b81828235528/ –

+0

我只是創建一個用戶控件和名稱是CustomUserControl 。用戶控件有一個文本框和一個按鈕。我只是試圖簡單地綁定該自定義列並出錯。錯誤與鑄造有關。我可能錯誤地使用了代碼來添加自定義列。如果任何人嘗試代碼,然後看到錯誤。如果有人指導我做什麼。謝謝 – Thomas

回答

-1

爲DataTables發佈一個名爲ColVis的新插件。 ColVis將在表格旁邊設置一個按鈕,該按鈕在激活時將顯示錶格中列的列表,最終用戶可以選擇顯示或隱藏列。

嘗試 datatables.net/release-datatables/extras/ColVis/

下載(放置提取的文件夾到的數據表分配 「額外」 文件夾): datatables.net/releases/ColVis-1.0 .1.zip

http://yellowpages.sulekha.com

+0

我只是不明白你想說什麼。在這裏我粘貼我的代碼,並試圖找出錯誤,但在這裏你談論另一種產品。 – Mou

+0

在這裏我談論Windows不是網絡應用程序。 – Mou