Winform DataGridView中利用WebClient异步加载显示网络地址的图片
Winform中的DataGridView,支持显示图片的一种列类型(Column Type),叫 DataGridViewImageColumn ,显示图片就是用这种列,但是这种列不支持网络地址,要显示网络上的图片,必须下载到本地,由于一个datagridview中显示的数据量可能比较大,如果每行的图片都是同步显示,则程序会长时间的BLOCK住,UE会很差,所以需要采用异步加载的方式。
/*-------------------------------------- * * Coding By DeltaCat * * http://www.zu14.cn * * 2008.11.21 * --------------------------------------*/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Net; using System.Windows.Forms; namespace DataGridView_WebImageColumn { public partial class Form1 : Form { public Form1() { InitializeComponent(); } /// <summary> /// 手动添加模拟数据 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { this.button1.Enabled = false; Random rnd = new Random(); 手动添加5条测试数据 for (int i = 1; i < 6; i++) { this.dataGridView1.Rows.Add(i.ToString(), "产品" + i.ToString(), string.Format( System.Globalization.CultureInfo.InvariantCulture, "¥{0:#.00}", rnd.NextDouble() * 10000), null); } } /// <summary> /// 处理dataGridView1的RowsAdded事件,在每行被载入后,即开始异步获取图片 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) { 利用 WebClient 来下载图片 using (WebClient wc = new WebClient()) { WebClient 下载完毕的响应事件绑定 wc.DownloadDataCompleted += new DownloadDataCompletedEventHandler(wc_DownloadDataCompleted); 开始异步下载,图片URL路径请根据实际情况自己去指定 同时将DataGridView当前行的行号传递过去,用于指定图片显示的CELL wc.DownloadDataAsync(new Uri(string.Format("http://www.zu14.cn/tip/{0}.gif", e.RowIndex + 5)), e.RowIndex); } } /// <summary> /// 图片下载完毕,显示于对应的CELL /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void wc_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e) { 如果下载过程未发生错误,并且未被中途取消 if (e.Error == null && !e.Cancelled) { 将图片显示于对应的指定单元格, e.UserState 就是传入的 e.RowIndex e.Result 就是下载结果 this.dataGridView1.Rows[(int)e.UserState].Cells["PictureColumn"].Value = e.Result; } } } }
DataGridViewImageColumn虽然支持显示图片,但默认情况下,不支持GIF动画,动画GIF图片,只显示第一帧,要显示动画图片,需做附加处理,后续…