-1

I create a class "Drink"

Drink have two variable

one is drink name, another is drink's picture

public class Drink
{
    public string name {get; set; }
    public Image pic {get; set; }
}

and initial it.

List<Drink> ex = new List<Drink>
{
   new Drink { name = "juice", pic = "Assets/juice.png" },
   new Drink { name = "water", pic = "Assets/water.png" }
};

but the pic's path is wrong, how set the picture to each?

Update: error message

pART
  • 43
  • 1
  • 9
  • What do you mean "but the pic's path is wrong", in what way is it wrong? I am betting you are getting a compiler error, if you are you could include that error as a edit to your question. – Scott Chamberlain Oct 20 '15 at 21:42
  • 2
    Your property is Image but you are initialising with a string. – DavidG Oct 20 '15 at 21:43
  • @ScottChamberlain sorry, english isn't my native language, I want set the file to pic, and i think "Assets.." is a path, so I say "path is wrong" – pART Oct 20 '15 at 22:38

2 Answers2

1

In your Drink class pic property is of type Image but you are assigning a string, it should be:

List<Drink> ex = new List<Drink>
{
   new Drink { name = "juice", pic = Image.FromFile("Assets/juice.png") },
   new Drink { name = "water", pic = Image.FromFile("Assets/water.png") }
};

Check Image.FromFile method on msdn.

w.b
  • 11,026
  • 5
  • 30
  • 49
  • but I don't see (.FromFile) TAT, have other way? – pART Oct 20 '15 at 22:42
  • @pART It depends on the framework you're using, is it WinForms, WPF etc? – w.b Oct 20 '15 at 22:45
  • @pART If it's xaml it's either WPF or WinRT, check these questions: http://stackoverflow.com/questions/11267257/programmatically-set-the-source-of-an-image-xaml , and http://stackoverflow.com/questions/11267257/programmatically-set-the-source-of-an-image-xaml – w.b Oct 20 '15 at 23:04
0

It's not totally clear what your asking, but you need to pass an Image in your initializer, not a string. In the example below Bitmap derives from Image:

List<Drink> ex = new List<Drink>
{
   new Drink { name = "juice", pic = new Bitmap("Assets/juice.png") },
   new Drink { name = "water", pic = new Bitmap("Assets/water.png") }
};
MikeH
  • 4,242
  • 1
  • 17
  • 32