Click here to Skip to main content
15,892,697 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have several images loaded in memory as Bitmaps.
I want to pass one of these memory Bitmaps from the main form to another as a Bitmap. The bitmap name is pulled from a datagrid where it is stored as a name string.

How can I get the bitmap name and turn that into the bitmap held in memory?
I can do it with a 'switch / case' type solution but thats a lot of mucking around and there is a lot of instances of this in the app. Hoping for something simpler.

What I have tried:

private Bitmap hazmat;
hazmat = new Bitmap(Properties.Resources.hazmat_30);

if (dgv1.Rows[rowID].Cells["ImageName"].Value != null)
   {
   string iName = dgv1.Rows[rowID].Cells["ImageName"].Value.ToString();  //'hazmat'
   //  formData.setPic(hazmat); //  this works fine but not whats needed.
   formData.setPic(Bitmap)iName); //  <- what goes here to reference the bitmap?
   }

In the target 'formData' form:
public void setPic(Bitmap pic)
{
    this.pb1.Image = pic;
}
Posted
Updated 28-Jan-18 21:18pm

A variable name can't easily be used to access a variable, particularly from a different class. You can do it using reflection, but ... you need the instance of the class that holds the private variable in order to do it, and that makes it even more messy!
That you are trying to do this shows there is something very wrong in your overall design, as this is not a good idea at all!

Instead, create a new class:
public class ImageContainer
    {
    public string Name { get; set; }
    public Image Image { get; set; }
    public override string ToString()
        {
        return Name;
        }
    }
And fill that with the image and name:
ImageContainer ic = new ImageContainer() { Name = "Hazmat", Image = hazmat };
Then use that class instance in your DataGridView. It will display the Name, but the cell will contain the ImageContainer.
Pass that to your second form:
if (dgv1.Rows[rowID].Cells["ImageName"].Value != null)
   {
   ImageContainer ic = (ImageContainer) dgv1.Rows[rowID].Cells["ImageName"].Value;
   formData.setPic(ic);
   }
public void setPic(ImageContainer ic)
    {
    pb1.Image = ic.Image;
    }
Clean, simple, easy to work with.
 
Share this answer
 
Hello, try this
C#
if (dgv1.Rows[rowID].Cells["ImageName"].Value != null)
{
   string iName = dgv1.Rows[rowID].Cells["ImageName"].Value.ToString();
   Bitmap bitmap = new Bitmap(iName);
   formData.setPic(bitmap);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900