简体   繁体   中英

I cannot change the image in pictureBox1 from code in C#

First things first: Im pretty new to Programming, and I'm trying to learn the C# Language

My Goal: Having a method that changes the picture in pictureBox1.

Issue: I get the error that tells me that an object reference is required for non-static field.

Here's a snippet of my class where the method should go.

private class Execute
{
    private void valueChecker(char value)
    {
        for (int i = 0; i <= charLenght; i++)
        {
            if (value != CharArray[i])
            {
                i++;
            }

            else if (value == CharArray[i])
            {
                CorrectLetter(value);
                svalue = true;
            }
        }
        if (svalue == true)
        {
            /* This is where the command is happening.
             But I get error message : "An object reference is required for the non-static field, method or property."
            */

            pictureBox1.Image = photos[x];
            x++;
        }
    }

}

I have also tried making new classes and methods other places in the code, and call it from the if statement, but I don't get this to work.

I need to change the picture in pictureBox1 if the svalue == true

A little further info on what exactly Im doing: Im making a hangman game as an exercise, and I want to update the Image in pictureBox1 if the input letter can't be found in the answer.

The pictures are stored in an array I have called photos[].

你的方法声明应该是这样的:

public void valueChecker(char value,PictureBox pictureBox1)
 var MyImage = new Bitmap(photos[x]);
 pictureBox1.Image = (Image) MyImage ;

Your class needs a reference to the PictureBox . You can add a property and set it after creating an instance of the class or even pass it right into the constructor..

private class Execute
{
   public PictureBox pBox {get; set;}

   public Execute(PictureBox  pb)
   {
        pBox  = pb;
   }

   private void valueChecker(char value)  // or maybe public ?!
   {
      ...
      ...

      if (pBox != null) pBox.Image = photos[x];
      x++;
    }
}

Create the class instance like this:

Execute someName = new Execute(pictureBox1);

Note that there are other ways to solve this; this is just a rather direct and straightforward one. If your class is a kind of service class you may want to go with Tarek's even more direct solution. Note that he not just adds the PictureBox to the parameter list. He also makes the function public .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM