[英]How to programmatically add a row to a datagridview when it is data-bound?
[英]How to render a data-bound WinForms DataGridView Column with an Icon?
在我的C#Windows Forms應用程序中,我有一個DataGridView
,它綁定到BindingList<Item>
列表,該列表又由List<Item>
初始化。
// bind view to controller
myDataGridView.DataBindings.Add("DataSource", myController, "Items");
// bind controller to model
Items = new BindingList<Item>(model.Items);
因此,根據類Item
的屬性生成datagrid的列。 我為DataGridView
的CellFormatting
事件提供了一個處理程序方法,以根據Item
類型的某些屬性值顯示某些單元格值:
myDataGridView.CellFormatting += new DataGridViewCellFormattingEventHandler(myontroller.HandleCellFormatting);
我現在還想將兩個可能的圖標之一添加到網格中的每一行,這也取決於Item
某些屬性的值。 請注意,現在與Items的任何屬性都具有直接對應關系,因此我在網格中沒有多余的列可容納圖標。 因此,猜測我必須將圖標添加到已經存在的單元格中,或者可能要即時生成適當的列。 有任何想法嗎 ?
您需要處理DataGridView
CellPainting
事件並自己繪制單元格。
例
本示例說明如何在DataGridView
的綁定列中繪制圖像,以便該列顯示綁定數據和圖像。 例如,在這里我決定為負數繪制一個紅色圖標,為零數繪制一個銀色圖標,為正數繪制一個綠色圖標:
為此,請定義一些變量以保留對圖像的引用。 我們將使用此變量來渲染圖像,並在不再需要它時將其處置:
Image zero, negative, positive;
從文件,資源或任何存儲圖像的位置處理表單和圖像的Load
事件,並將其分配給這些變量。 設置數據綁定。 為要在其中繪制圖標的單元格設置合適的左填充:
private void Form1_Load(object sender, EventArgs e)
{
var list = new[] {
new { C1 = "A", C2 = -2 },
new { C1 = "B", C2 = -1 },
new { C1 = "C", C2 = 0 },
new { C1 = "D", C2 = 1 },
new { C1 = "E", C2 = 2 },
}.ToList();
dataGridView1.DataSource = list;
zero = new Bitmap(16, 16);
using (var g = Graphics.FromImage(zero))
g.Clear(Color.Silver);
negative = new Bitmap(16, 16);
using (var g = Graphics.FromImage(negative))
g.Clear(Color.Red);
positive = new Bitmap(16, 16);
using (var g = Graphics.FromImage(positive))
g.Clear(Color.Green);
//Set padding to have enough room to draw image
dataGridView1.Columns[1].DefaultCellStyle.Padding = new Padding(18, 0, 0, 0);
}
處理DataGridView
CellPainting
事件,並為所需的列呈現單元格內容和圖像:
private void DataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
//We don't need custom paint for row header or column header
if (e.RowIndex < 0 || e.ColumnIndex != 1) return;
//We don't need custom paint for null value
if (e.Value == null || e.Value == DBNull.Value) return;
//Choose image based on value
Image img = zero;
if ((int)e.Value < 0) img = negative;
else if ((int)e.Value > 0) img = positive;
//Paint cell
e.Paint(e.ClipBounds, DataGridViewPaintParts.All);
e.Graphics.DrawImage(img, e.CellBounds.Left + 1, e.CellBounds.Top + 1,
16, e.CellBounds.Height - 3);
//Prevent default paint
e.Handled = true;
}
處理FormClosing
事件以處理圖像:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//Dispose images
if (zero != null) zero.Dispose();
if (negative != null) negative.Dispose();
if (positive != null) positive.Dispose();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.