C# Winform DataGridView中利用WebClient异步加载显示网络图片

Winform中的DataGridView,支持显示图片的一种列类型(Column Type),叫 DataGridViewImageColumn ,显示图片就是用这种列,但是这种列不支持网络地址,要显示网络上的图片,必须下载到本地,由于一个datagridview中显示的数据量可能比较大,如果每行的图片都是同步显示,则程序会长时间的BLOCK住,UE会很差,所以需要采用异步加载的方式。代码如下:

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>
private void button1_Click(object sender, EventArgs e)
{
this.button1.Enabled = false;

Random rnd = new Random();

手动添加5条测试数据
for (int i = 1; i &lt; 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>
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
利用 WebClient 来下载图片
using (WebClient wc = new WebClient())
{
WebClient 下载完毕的响应事件绑定
wc.DownloadDataCompleted += newDownloadDataCompletedEventHandler(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>
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;
}
}
}
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值