C#中 - 在同一行图像和文本 - 的DataGridView图像、文本、DataGridView

2023-09-03 02:55:33 作者:亿人不及你一人

我要寻找这样的事情在DataGridView的:

I am looking for something like this on DataGridView:

Image  | Text | 
Text   | Text |
Image  | Text

基本上,我只是想在同一行图像细胞和细胞的文本。 我能得到它与不同类型的工作,例如:复选框,文本,等... 但我不能够得到它处理图像。

Basically, I just want Image cells and Text cells on the same row. I was able to get it to work with different types, for example: Checkbox, Text, and etc... But I am not able to get it to work with images.

我得到这个错误:无效的转换从'System.String'的,以为System.Drawing.Image

有谁知道解决的办法或者有建议的,我应该怎么办呢? 谢谢

Does anybody know the solution or have suggestion on how I should do this ? Thanks

推荐答案

这是比较容易有类型的列 DataGridViewImageColumn 显示在某些细胞的文本。

It is relatively easy to have a column of type DataGridViewImageColumn display text in certain cells.

所有你需要做的是更换所需电池的 DataGridViewTextBoxCell

All you need to do is replace a desired cell with a DataGridViewTextBoxCell.

因此​​,举例来说,如果我下面的图像列添加到我的网格:

So for example, if I add the following image column to my grid:

DataGridViewImageColumn imageColumn = new DataGridViewImageColumn();
imageColumn .Name = "ImageColumn";
imageColumn .HeaderText = "An Image!";
Image i = Image.FromFile(@"C:\Pictures\TestPicture.jpg");
imageColumn.Image = i;
dataGridView1.Columns.Add(imageColumn);

您可以用文本替换特定的细胞像这样(在这里一个按钮处理程序,但你也可以做到这一点的地方像一个绑定完整的处理程序中)。

You can replace a given cell with text like so (here in a button handler but you could also do it somewhere like within a databinding complete handler).

private void button1_Click(object sender, EventArgs e)
{
    dataGridView1.Rows[3].Cells["ImageColumn"] = new DataGridViewTextBoxCell();
    dataGridView1.Rows[3].Cells["ImageColumn"].Value = "Some text!";  
}

如果你想不同的图像(需要绑定类型图像的属性),如果你想不同的文本此解决方案留下了你的工作​​一点点。由于图像列的值属性的类型图片的,你不能使用相同的绑定。

This solution leaves a little bit of work for you if you want different images (you need to bind to a property of type image) and if you want different text. Since the Value property of an image column is of type Image you cannot use the same binding.

您可以作出这样的处理,这是你自己的重写的image列,但它是一些工作,可能不支付本身与简单的设置值在您想直接文本的单元格。

You could make your own overridden image column that handled this, but it would be a bit of work, that might not pay for itself vs. simply setting the value for the cells where you want text directly.

 
精彩推荐
图片推荐