在表单之间传递位图,但由字符串引用 [英] Pass a bitmap between forms but referenced by a string

查看:82
本文介绍了在表单之间传递位图,但由字符串引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在内存中加载了几个图像作为位图。

我想将其中一个内存位图从主窗体传递到另一个作为位图。位图名称是从数据网格中提取的,它存储为名称字符串。



如何获取位图名称并将其转换为内存中保存的位图?

我可以使用'switch / case'类型的解决方案做到这一点,但这有很多问题,应用程序中有很多这样的实例。希望更简单。



我尝试过:



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



在目标'formData'表格中:


In the target 'formData' form:

public void setPic(Bitmap pic)
{
    this.pb1.Image = pic;
}

推荐答案

变量名称不能轻易用于访问变量,特别是来自a不同的阶级。你可以使用反射来做到这一点,但是......你需要拥有私有变量的类的实例才能做到这一点,这会让它变得更加混乱!

你想要的这表明你的整体设计有些不对劲,因为这根本不是一个好主意!



相反,创建一个新类:

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

并用图像和名称填写:

ImageContainer ic = new ImageContainer() { Name = "Hazmat", Image = hazmat };

然后在DataGridView中使用该类实例。它将显示Name,但单元格将包含ImageContainer。

将其传递给您的第二个表单:

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.


您好,试试这个

Hello, try this
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);
}


这篇关于在表单之间传递位图,但由字符串引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆