I need to know whether the PictureBox
contains an Image
in a specified imageList
. Because if ImageList is long, it will take a lot to say in an if-statement
if each image in imageList
is in the PictureBox. and when I type
foreach (var image in imageList1)
{
if (pictureBox1.Image = image)
{
//Code
}
}
It doesn't work :/
Try the following:
//using System.Linq;
bool isinside = /*yourImageList*/.Images.Any(x => x == /*yourPictureBox*/.Image);
if (isinside)
{
//is in yourImageList
MessageBox.Show("image is from imagelist!");
//or do what you want here!
}
ImageList
is a special thing and it may or may not be the right object to use..
One good thing about it is that it stores the images not as type Image
; this is good because it doesn't need a GDI
handle for each image it stores, even if you add a large number of images.
One problem with this is that you simply can't compare its images to an image you have assigned to a PictureBox.Image
.
So even after correcting your syntax this will not work:
// assign an image
pictureBox1.Image = imageList1.Images[2];
// now look for it:
foreach (var img in imageList1.Images)
{
if (pictureBox1.Image == img )
{
Console.WriteLine("Found the Image!"); // won't happen
}
}
Instead you should store the Key
to the image in the ImageList
:
pictureBox1.Image = imageList1.Images[2];
pictureBox1.Tag = imageList1.Images.Keys[2];
Now you can easily look for the key:
foreach (var imgKey in imageList1.Images.Keys)
{
if (pictureBox1.Tag.ToString() == imgKey )
{
Console.WriteLine("Found the Image-Key!"); // will happen quite quickly!
}
}
Of course the question if using an ImageList
is a good idea in the first place is quite another matter..
It is really meant to be used with ListViews
, TreeViews
and other Controls that can display small iconic images.
It is limited to 256x256 pixels for instance; also: all its images must have the same size!
But if that is OK, stay with it.
Otherwise a List<Image>
, as Hans suggested would be a natural and flexible alternative..
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.