场景:在数据库中,我们有一个varchar类型的列,其中包含要显示的图像的路径,在dotnet应用程序中,我们有一个gridview,其中包含varchar类型的列。现在,在此列中,我们需要显示应用程序项目图像文件夹中的图像。
我们正在使用下面的方法,但是使用gridviewimagecolumn
编写System.drawing.bitmapforeach (DataGridViewRow row1 in dgvDisplayTiles.Rows)
{
string imgPath;
imgPath= (Application.StartupPath + row1.Cells[3].Value.ToString());
Image imageFile = Image.FromFile(imgPath);
if (imgPath != null)
{
//img.Image=imgPath;
row1.Cells[3].Value = imageFile;
}
else
{
MessageBox.Show("Invalid Path");
}
}
答案 0 :(得分:1)
问题在于你合并错误的路径。
你应该使用:
imgPath= Path.Combine(Application.StartupPath, row1.Cells[3].Value.ToString());
而不是:
imgPath= (Application.StartupPath + row1.Cells[3].Value.ToString());
完整代码:
foreach (DataGridViewRow row1 in dgvDisplayTiles.Rows)
{
string imgPath;
imgPath= Path.Combine(Application.StartupPath, row1.Cells[3].Value.ToString());
Image imageFile = Image.FromFile(imgPath);
if (imgPath != null)
{
//img.Image=imgPath;
row1.Cells[3].Value = imageFile;
}
else
{
MessageBox.Show("Invalid Path");
}
}
更新#2:
您可以像这样创建动态列:
为了便于理解,我创建了一个Employee类并添加了一些虚拟数据并将其与DataGridView绑定
public class Employee
{
public string id { get; set; }
public string name { get; set; }
public string imagePath { get; set; }
}
private void bindGrid()
{
List<Employee> employees = new List<Employee>();
employees.Add(new Employee() { id = "1",name = "joseph", imagePath = "abc.png" });
employees.Add(new Employee() { id = "2", name = "Mac", imagePath = "capture2.png" });
this.dataGridView1.DataSource = employees;
DataGridViewImageColumn column = new DataGridViewImageColumn();
column.Name = "imgColumn1";
column.HeaderText = "Image";
this.dataGridView1.Columns.Add(column);
this.dataGridView1.Refresh();
foreach (DataGridViewRow row1 in dataGridView1.Rows)
{
string imgPath;
imgPath = Path.Combine(Application.StartupPath, row1.Cells[2].Value.ToString());
Image imageFile = Image.FromFile(imgPath);
if (imgPath != null)
{
row1.Cells[3].Value = imageFile;
}
else
{
MessageBox.Show("Invalid Path");
}
}
}