display the retrieved image URL from the SQL to the DataGridView

Ahmed Babajan 21 Reputation points
2023-01-06T21:03:34.147+00:00

Hello .

I set all the codes to retrieve the information from the SQL table , now i only need to convert the retrieved image URL to Image in the DataGridView
277032-123.png

here is the codes i am using now :

    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;  
    }  

and on the class here is the codes :

             public class Products  
                      {  
                           public int Id { get; set; }  
                           public string? Date { get; set; }  
                           public string? Customer { get; set; }  
                           public string? Product { get; set; }  
                           public int Qty { get; set; }  
                           public decimal Price { get; set; }  
                           public decimal Selling { get; set; }  
                           public string? Image { get; set; }  
                           public string? Status { 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 Id, Date, Customer, Product, Qty, Price, Selling, 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.Id = Convert.ToInt32(dr["Id"]);  
                Products.Date = dr["Date"].ToString();  
                Products.Customer = dr["Customer"].ToString();  
                Products.Product = dr["Product"].ToString();  
                Products.Qty = Convert.ToInt32(dr["Qty"]);  
                Products.Price = Convert.ToInt64(dr["Price"]);  
                Products.Selling = Convert.ToInt64(dr["Selling"]);  
                Products.Image = dr["Image"].ToString();  
                Products.Status = dr["Status"].ToString();  



                ProductsList.Add(Products);  
            }  
        }  

        return ProductsList;  

    }  
Developer technologies Windows Forms
{count} votes

Accepted answer
  1. Jack J Jun 25,296 Reputation points
    2023-01-09T02:17:33.363+00:00

    @Ahmed Babajan , Welcome to Microsoft Q&A, I recommend that you re-add the column one by one instead of using dataGridViewProducts.DataSource = productsList;, which may force your Image column is string type. We need to add the DataGridViewImageColumn to your current datagirdview. Here is a code example you could refer to. First method:

    code.txt Second method: We need to change Image type in your model class:

    public class Products
    {
        ...
        public Image? img { get; set; }
    
    }
    
      {
                             Products Products = new Products();
                             Products.Id = Convert.ToInt32(dr[&#34;Id&#34;]);
                             Products.Date = dr[&#34;Date&#34;].ToString();
                             Products.Customer = dr[&#34;Customer&#34;].ToString();
                             Products.Product = dr[&#34;Product&#34;].ToString();
                             Products.Qty = Convert.ToInt32(dr[&#34;Qty&#34;]);
                             Products.Price = Convert.ToInt64(dr[&#34;Price&#34;]);
                             Products.Selling = Convert.ToInt64(dr[&#34;Selling&#34;]);
                             string imageurl =dr[&#34;Image&#34;].ToString();
                             var request = WebRequest.Create(imageurl);
                             Image im = null;
                             using (var response = request.GetResponse())
                             using (var stream = response.GetResponseStream())
                             {
                             im = Bitmap.FromStream(stream);
                             }
                             Products.img= im;
                             Products.Status = dr[&#34;Status&#34;].ToString();
            
            
                             ProductsList.Add(Products);
                         }
    

    Result:

    277197-image.png

    Best Regards, Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. Reza Aghaei 4,986 Reputation points MVP Volunteer Moderator
    2023-01-14T11:41:11.0833333+00:00

    You already have an answer for your question that you asked in stackoverflow:

    In the code example, I've handled the CellFormatting event, considering the following points:

    • The code loads images lazily, once requested in CellFormattings using HttpClient, so it doesn't load the images which are not in viewport, but as soon as the come to viewport, it downloads them.
    • The code load images using task-based API, so the app will not freeze.
    • It stores image in the cell value, to avoid loading it again.

    enter image description here

    Here's a modified version based on your new question here, which uses a POCO as model.

    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Net.Http;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            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 = (Product)dgv1.Rows[e.RowIndex].DataBoundItem;
                    var uri = item.ImageUri;
                    if (e.Value == null)
                    {
                        dgv1.Rows[e.RowIndex]
                            .Cells["ImageColumn"].Value = await DownloadImage(uri);
                    }
                }
            }
            List<Product> GetData()
            {
                var data = new List<Product>();
                data.Add(new Product() { Name = "Lorem", ImageUri = $"https://picsum.photos/300/200?1" });
                data.Add(new Product() { Name = "Lorem", ImageUri = $"https://picsum.photos/300/200?2" });
                data.Add(new Product() { Name = "Lorem", ImageUri = $"https://picsum.photos/300/200?3" });
                data.Add(new Product() { Name = "Lorem", ImageUri = $"https://picsum.photos/300/200?4" });
                data.Add(new Product() { Name = "Lorem", ImageUri = $"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));
            }
        }
        public class Product
        {
            public string Name { get; set; }
            public string ImageUri { get; set; }
        }
    }
    
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.