问题描述:

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)

{

}

}

}

网友答案:

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()

网友答案:

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?

网友答案:

Remove the following lines:

class MyClass {

相关阅读:
Top