-1

Can someone help...Please! I keep getting the following error?

An object reference is required for the non-static field, method, or property 'MyClass.SetImageUrl()'

Here is the code...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ThreeTierWebApp
{
    class MyClass
    {

        public partial class Holidays : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)

            {
                if (!IsPostBack)
                {
                    SetImageUrl();
                }

            }

        }

        protected void Timer1_Tick(object sender, EventArgs e)
        {
            SetImageUrl();

        }

        private void SetImageUrl()
        {
            Random _rand = new Random();
            int i = _rand.Next(9, 16);
            Image5.ImageUrl = "~/Images/" + i.ToString() + ".jpg";
        }

        protected void MultiView1_ActiveViewChanged(object sender, EventArgs e)
        {

        }
    }
}
shlatchz
  • 1,612
  • 1
  • 18
  • 40
RockyV
  • 3
  • 1
  • make your method public. – Radmation Apr 22 '16 at 22:38
  • Your code is weird. Why is the partial class Holidays inside your MyClass class ? – HaukurHaf Apr 22 '16 at 22:38
  • 1
    It is a scoping issue. SetImageUrl() is outside of the class you are calling it from (hard to tell for sure) and the method is private. – Radmation Apr 22 '16 at 22:40
  • Possible duplicate of [Error: "an object reference is required for the non-static field, method or property..."](http://stackoverflow.com/questions/2505181/error-an-object-reference-is-required-for-the-non-static-field-method-or-prop) –  Apr 22 '16 at 22:40
  • Delete enveloping class `class MyClass() { }` and move its functions to `class Holidays() { }` – shlatchz Apr 22 '16 at 22:41

3 Answers3

2

You are calling a non-static method on an outer class. Either: make the SetImageUrl a static method Or: Pass a reference of an instance of MyClass to the instance of Holidays that you create.

Or maybe the nesting is just a mistake, and SetImageUrl was suppose to be a member of Holidays?

0

Remove the following lines:

class MyClass {

KSib
  • 893
  • 1
  • 7
  • 24
0

Change

private void SetImageUrl()
{
    Random _rand = new Random();
    int i = _rand.Next(9, 16);
    Image5.ImageUrl = "~/Images/" + i.ToString() + ".jpg";
}

to

public void SetImageUrl()
{
        Random _rand = new Random();
        int i = _rand.Next(9, 16);
        Image5.ImageUrl = "~/Images/" + i.ToString() + ".jpg";
}

I agree your code is weird. You may have to make the Method Static and call it like: MyClass.SetImageUrl()

Radmation
  • 1,486
  • 1
  • 13
  • 30