我需要将整个DataGridView保存为图像。
我在网上看到过一些帖子,但对我不起作用。
到目前为止,我已经尝试了以下两个链接:
DataGridView to Bimap和Save Image in folder。
我的意图是,一旦按下按钮,DataGridView将被转换为图像,并将其自动保存到桌面。
我使用的代码会产生错误:
GDI +中发生一般错误
private void button1_Click(object sender, EventArgs e)
{
//Resize DataGridView to full height.
int height = dataGridView1.Height;
dataGridView1.Height = dataGridView1.RowCount * dataGridView1.RowTemplate.Height;
//Create a Bitmap and draw the DataGridView on it.
Bitmap bitmap = new Bitmap(this.dataGridView1.Width, this.dataGridView1.Height);
dataGridView1.DrawToBitmap(bitmap, new Rectangle(0, 0, this.dataGridView1.Width, this.dataGridView1.Height));
//Resize DataGridView back to original height.
dataGridView1.Height = height;
//Save the Bitmap to folder.
bitmap.Save(@"C:\\Desktop\\datagrid.jpg");
}
希望获得一些帮助。谢谢!
答案 0 :(得分:1)
尝试
图像保存文件路径,例如“ C:\ Users \ User \ Desktop \ datagrid.jpg ”
bitmap.Save(@"C:\Users\User\Desktop\datagrid.jpg");
答案 1 :(得分:1)
您需要修复代码的多个部分:
bitmap.Save(@"C:\\Desktop\\datagrid.jpg");
。此路径字符串应为:@"C:\Users\SomeUser\Desktop\datagrid.jpg"
或"C:\\Users\\SomeUser\\Desktop\\datagrid.jpg"
。参见第6点。Bitmap
对象时,必须将该对象与您创建的任何其他一次性对象一样进行处理。您可以使用Bitmap.Dispose()方法或将对象封装在Using块中。Bitmap.Save([Path])
(未指定ImageFormat)将创建PNG
图像。不考虑您在Path字符串中插入的文件扩展名。目前,您正在创建一个扩展名为.jpg
的文件,而实际上它是一个.png
文件。Png
格式,而不要使用Jpeg
格式。其无损压缩更具吸引力:它将保留图像颜色并提高整体质量。您可以如下修改代码:
using System.IO;
private void button1_Click(object sender, EventArgs e)
{
int DGVOriginalHeight = dataGridView1.Height;
dataGridView1.Height = (dataGridView1.RowCount * dataGridView1.RowTemplate.Height) +
dataGridView1.ColumnHeadersHeight;
using (Bitmap bitmap = new Bitmap(this.dataGridView1.Width, this.dataGridView1.Height))
{
dataGridView1.DrawToBitmap(bitmap, new Rectangle(Point.Empty, this.dataGridView1.Size));
string DesktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
bitmap.Save(Path.Combine(DesktopFolder, "datagridview1.png"), ImageFormat.Png);
}
dataGridView1.Height = DGVOriginalHeight;
}
答案 2 :(得分:0)
尝试将flatMap
替换为:
import { flatMap } from 'rxjs/operators';
this.getCities().pipe(
flatMap(cities => {
this.cities = cities;
return this.getEmployerLocations();
}),
flatMap(locations => {
this.locations = locations;
this.locations.forEach( location => {
location.city = this.getCityById( location.cityId ); // from cities received: this.cities
});
return this.getEmployerShifts();
})
).subscribe(shifts => {
this.shifts = shifts;
this.shifts.forEach( shift => {
this.shift.location = this.getShiftLocationById( shift.locationId ); // from locations received: this.locations
});
});