我在搜索技巧,將用戶控件添加到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
,但沒有運氣。謝謝
你有什麼錯誤?你能過去你的錯誤嗎? –
請看這個好樣本:http://social.msdn.microsoft.com/forums/en-US/winformsdatacontrols/thread/ee8eec0b-2b1a-46d2-9d2e-b81828235528/ –
我只是創建一個用戶控件和名稱是CustomUserControl 。用戶控件有一個文本框和一個按鈕。我只是試圖簡單地綁定該自定義列並出錯。錯誤與鑄造有關。我可能錯誤地使用了代碼來添加自定義列。如果任何人嘗試代碼,然後看到錯誤。如果有人指導我做什麼。謝謝 – Thomas