![](/img/trans.png)
[英]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.