0

the SS of my current App

1

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

here is the codes 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 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;

    }

Anyone have any idea on how to show the image ? from URL

2
  • It's your Products (should be single) class that needs to retrive the Image when you pass the URI to it -- You should probably avoid naming a Property Image, when it actually stores the ImageUri. When you do that, it's also easier to retrieve a thumbnail of the real image, then show the original (larger) image when / if required
    – Jimi
    Jan 7 at 20:09
  • sorry i didn't understand , i just upload SS image , please check it out Jan 7 at 20:31

1 Answer 1

0

The easiest solution is using an unbound DataGridViewImageColumn, then you can handle CellFormatting event and load the image.

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

  • The code loads images lazily, once requested in CellFormattings.
  • It stores image in the cell value, to avoid loading it again.

enter image description here

To try the code, create a Form, drop a DataGridView on it and use the following code:

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

Run the code and see the result.

You should also take care of disposing the images:

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

    }
}

You may also want to modify the code and handle cases when the image could not be downloaded.

1
  • It looks like the post answers your question. Did you forget to accept the answer? Jan 15 at 19:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.