winforms 如何在DataGridView中显示来自检索到的图像URL的图像

nnvyjq4y  于 2023-01-09  发布在  其他
关注(0)|答案(1)|浏览(139)

我当前应用程序的SS

我设置了所有代码以从SQL表中检索信息,现在我只需要将检索到的图像URL转换为DataGridView中的Image

以下是我现在使用的代码:

namespace LamasoDemo
    {
             public partial class FormOrders : Form
             {
                public FormOrders()
                 {
                   InitializeComponent();
                   FillGridView();
                 }

    
    void FillGridView()
    {
        List<Products> productsList = new List<Products>();
        Products products = new Products();
        productsList = products.GetProducts();
        dataGridViewProducts.DataSource = productsList;
    }

在类上,这里是代码:

public class Products
    {
       
       public string? Image { get; set; }
       
    

string connectionString = "Data Source=AHMEDBABAJAN;Initial Catalog=Lamaso1;Integrated Security=True;Trust Server Certificate=true";

    
    public List<Products> GetProducts()
    {
        List<Products> ProductsList = new List<Products>();
        SqlConnection con = new SqlConnection(connectionString);

        string selectSQL = "select  Image Status From GetProductsData";
        con.Open();

        SqlCommand cmd = new SqlCommand(selectSQL, con);
        SqlDataReader dr = cmd.ExecuteReader();

        if (dr != null)
        {
            while (dr.Read())
            {
                Products Products = new Products();

                
                Products.Image = dr["Image"].ToString();
                
                ProductsList.Add(Products);
            }
        }

        return ProductsList;

    }

任何人都有任何关于如何显示图像的想法?从URL

waxmsbnn

waxmsbnn1#

最简单的解决方案是使用未绑定的DataGridViewImageColumn,然后您可以处理CellFormatting事件并加载图像。
在下面的示例中,我处理了CellFormatting事件,考虑了以下几点:

  • 一旦在CellFormattings中请求,代码就会延迟加载图像。
  • 它将图像存储在单元格值中,以避免再次加载。

若要尝试该代码,请创建一个窗体,将DataGridView拖放到该窗体上,然后使用下面的代码:

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    httpClient.DefaultRequestHeaders.TryAddWithoutValidation(
        "User-Agent", "Mozilla/5.0 (Windows NT 6.2; " +
        "WOW64; rv:19.0) Gecko/20100101 Firefox/19.0");

    //Load data
    var data = GetData();

    //Set up dataGridView 
    dgv1.RowTemplate.Height = 100;
    dgv1.DataSource = data;
    dgv1.Columns.Add(new DataGridViewImageColumn()
    {
        Name = "ImageColumn",
        HeaderText = "Image",
        ImageLayout = DataGridViewImageCellLayout.Zoom,
        Width = 150
    });
    dgv1.CellFormatting += dgv1_CellFormatting;
}
private async void dgv1_CellFormatting(object sender,
    DataGridViewCellFormattingEventArgs e)
{
    if (e.RowIndex >= 0 && e.RowIndex < dgv1.NewRowIndex &&
        dgv1.Columns[e.ColumnIndex].Name == "ImageColumn")
    {
        var item = (DataRowView)dgv1.Rows[e.RowIndex].DataBoundItem;
        var uri = item.Row.Field<string>("ImageUri");
        if (e.Value == null || e.Value == DBNull.Value)
        {
            dgv1.Rows[e.RowIndex]
                .Cells["ImageColumn"].Value = await DownloadImage(uri);
        }
    }
}
DataTable GetData()
{
    var data = new DataTable();
    data.Columns.Add("Name", typeof(string));
    data.Columns.Add("ImageUri", typeof(string));
    data.Rows.Add("Lorem", $"https://picsum.photos/300/200?1");
    data.Rows.Add("Ipsum", $"https://picsum.photos/300/200?2");
    data.Rows.Add("Dolor", $"https://picsum.photos/300/200?3");
    data.Rows.Add("Sit", $"https://picsum.photos/300/200?4");
    data.Rows.Add("Amet", $"https://picsum.photos/300/200?5");
    return data;
}

HttpClient httpClient = new HttpClient();
async Task<Image> DownloadImage(string uri)
{
    return Image.FromStream(await httpClient.GetStreamAsync(uri));
}

运行代码并查看结果。
您还应注意处理图像:

protected override void OnFormClosing(FormClosingEventArgs e)
{
    base.OnFormClosing(e);
    if (!e.Cancel)
    {
        DisposeImages();
    }
}
void DisposeImages()
{
    foreach (DataGridViewRow row in dgv1.Rows)
    {
        if (!row.IsNewRow)
        {
            var value = row.Cells["ImageColumn"].Value;
            row.Cells["ImageColumn"].Value = null;
            if (value is Image)
                ((Image)value).Dispose();
        }

    }
}

您可能还希望修改代码并处理无法下载映像的情况。

相关问题