Search code, repositories, users, issues, pull requests…
Provide feedback
Saved searches
Use saved searches to filter your results more quickly
Sign up
Consider:
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//int[] val = { 0, 0};
int val;
if (textBox1.Text == "")
{
MessageBox.Show("Input any no");
}
else
{
val = Convert.ToInt32(textBox1.Text);
Thread ot1 = new Thread(new ParameterizedThreadStart(SumData));
ot1.Start(val);
}
}
private static void ReadData(object state)
{
System.Windows.Forms.Application.Run();
}
void setTextboxText(int result)
{
if (this.InvokeRequired)
{
this.Invoke(new IntDelegate(SetTextboxTextSafe), new object[] { result });
}
else
{
SetTextboxTextSafe(result);
}
}
void SetTextboxTextSafe(int result)
{
label1.Text = result.ToString();
}
private static void SumData(object state)
{
int result;
//int[] icount = (int[])state;
int icount = (int)state;
for (int i = icount; i > 0; i--)
{
result += i;
System.Threading.Thread.Sleep(1000);
}
setTextboxText(result);
}
delegate void IntDelegate(int result);
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
Why is this error occurring?
An object reference is required for the nonstatic field, method, or property ‘WindowsApplication1.Form1.setTextboxText(int)
VertigoRay
5,9556 gold badges39 silver badges48 bronze badges
asked Jan 31, 2009 at 6:22
It looks like you are calling a non static member (a property or method, specifically setTextboxText) from a static method (specifically SumData). You will need to either:
- If you can, make
setTextboxTextstatic:
static void setTextboxText(int result)
HOWEVER, in this case, setTextboxText REQUIRES access to instance variables, so cannot be static.
Instead do:
- Call
setTextboxTextvia a static singleton of Form1:
class Form1
{
public static Form1 It; // Singleton.
public Form1()
{
It = this;
}
private static void SumData(object state)
{
...
It.setTextboxText(result);
}
}
-
Create an instance of
Form1within the calling method:private static void SumData(object state) { int result = 0; //int[] icount = (int[])state; int icount = (int)state; for (int i = icount; i > 0; i--) { result += i; System.Threading.Thread.Sleep(1000); } Form1 frm1 = new Form1(); frm1.setTextboxText(result); }BUT that won’t do what you want, if an instance of Form1 already exists.
Passing in an instance ofForm1would be an option also. -
Make the calling method a non-static instance method (of
Form1):private void SumData(object state) { int result = 0; //int[] icount = (int[])state; int icount = (int)state; for (int i = icount; i > 0; i--) { result += i; System.Threading.Thread.Sleep(1000); } setTextboxText(result); }
More info about this error can be found on MSDN.
answered Jan 31, 2009 at 6:28
0
For this case, where you want to get a Control of a Form and are receiving this error, then I have a little bypass for you.
Go to your Program.cs and change
Application.Run(new Form1());
to
public static Form1 form1 = new Form1(); // Place this var out of the constructor
Application.Run(form1);
Now you can access a control with
Program.form1.<Your control>
Also: Don’t forget to set your Control-Access-Level to Public.
And yes I know, this answer does not fit to the question caller, but it fits to googlers who have this specific issue with controls.
answered Jan 7, 2017 at 20:28
You start a thread which runs the static method SumData. However, SumData calls SetTextboxText which isn’t static. Thus you need an instance of your form to call SetTextboxText.
answered Jan 31, 2009 at 8:40
Brian RasmussenBrian Rasmussen
115k34 gold badges221 silver badges317 bronze badges
2
Your method must be static
static void setTextboxText(int result)
{
if (this.InvokeRequired)
{
this.Invoke(new IntDelegate(SetTextboxTextSafe), new object[] { result });
}
else
{
SetTextboxTextSafe(result);
}
}
answered Jul 1, 2014 at 13:16
1
Credit to @COOLGAMETUBE for tipping me off to what ended up working for me. His idea was good but I had a problem when Application.SetCompatibleTextRenderingDefault was called after the form was already created. So with a little change, this is working for me:
static class Program
{
public static Form1 form1; // = new Form1(); // Place this var out of the constructor
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(form1 = new Form1());
}
}
answered Jul 27, 2018 at 2:34
veggiebenzveggiebenz
3895 silver badges12 bronze badges
Make the function static. This must solve your problem.
answered Oct 1, 2021 at 10:19
0
I actually got this error because I was checking InnerHtml for some content that was generated dynamically — i.e. a control that is runat=server.
To solve this I had to remove the «static» keyword on my method, and it ran fine.
answered Jun 3, 2019 at 15:17
The essence, and solution, to your problem is this:
using System;
namespace myNameSpace
{
class Program
{
private void method()
{
Console.WriteLine("Hello World!");
}
static void Main(string[] args)
{
method();//<-- Compile Time error because an instantiation of the Program class doesnt exist
Program p = new Program();
p.method();//Now it works. (You could also make method() static to get it to work)
}
}
}
answered May 2, 2021 at 0:05
Dean PDean P
1,84123 silver badges23 bronze badges
From my looking you give a null value to a textbox and return in a ToString() as it is a static method. You can replace it with Convert.ToString() that can enable null value.
answered Jan 12, 2013 at 12:20
Getting this error when I submit my form to savetext.aspx action file:
Compiler Error Message: CS0120: An object reference is required for the nonstatic field, method, or property 'System.Web.UI.Page.Request.get'
On this line:
string path = "/txtfiles/" + Request.Form["file_name"];
Whole code:
<%@ Page Language="C#" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.IO" %>
<script runat="server">
class Test
{
public static void Main()
{
string path = "/txtfiles/" + Request.Form["file_name"];
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine(request.form["seatsArray"]);
sw.WriteLine("");
}
}
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
}
</script>
How do I fix it?
Thanks!
asked Jul 14, 2010 at 14:48
6
Remove this Test class as well as the static Main method and replace it with a Page_Load instance method like so:
<%@ Page Language="C#" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.IO" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
string path = "/txtfiles/" + Request.Form["file_name"];
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine(Request.Form["seatsArray"]);
sw.WriteLine("");
}
}
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Response.Write(s);
}
}
}
</script>
Also you probably want to output to the HttpResponse instead of a console in a web application. Another remark is about your file path: "/txtfiles/", NTFS usually doesn’t like such patterns.
answered Jul 14, 2010 at 14:53
Darin DimitrovDarin Dimitrov
1.0m271 gold badges3288 silver badges2930 bronze badges
0
Darin Dimitrov gave you a hint in right direction, but i want just to give answer to question why does this error happen. Normal error should be:
The name ‘Request’ does not exist in
the current context
This happen because for each aspx file a class is created that inherits from Page by default. All new classes defined inside aspx file become nested classes of that one. Request is member of class Page and this particular error happen because you try to access it from static method of nested type.
answered Jul 14, 2010 at 15:13
AndreyAndrey
59.1k12 gold badges120 silver badges163 bronze badges
I’m getting the error ‘An object reference is required for the nonstatic field, method, or property ‘ when I attempt to run my application in Visual Web Developer. I am not sure what is wrong and I’m new to programming, and I’m following examples from a book. The page allows a logged in user to view their profile which the attributes such as Firstnames, Lastnames etc. are within my web.config file. Does anyone know what I am doing wrong? My error, along with code, is below. Thanks in advance!
Compiler Error Message: CS0120: An object reference is required for the nonstatic field, method, or property ‘System.Web.UI.Control.FindControl(string)’
Source Error:
|
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
public partial class SecurePage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated == false)
{
Server.Transfer(«login.aspx»);
}
if (!Page.IsPostBack)
{
DisplayProfileProperties();
}
}
protected void CancelButton_Click(object sender, EventArgs e)
{
DisplayProfileProperties();
}
protected void SaveButton_Click(object sender, EventArgs e)
{
Profile.Firstnames = ((TextBox)LoginView.FindControl(«FirstNamesTextBox»)).Text;
Profile.Lastname = ((TextBox)LoginView.FindControl(«LastNameTextBox»)).Text;
Profile.FirstLineOfAddress = ((TextBox)LoginView.FindControl(«FirstLineOfAddressTextBox»)).Text;
Profile.SecondLineOfAddress = ((TextBox)LoginView.FindControl(«SecondLineOfAddressTextBox»)).Text;
Profile.TownOrCity = ((TextBox)LoginView.FindControl(«TownOrCityTextBox»)).Text;
Profile.County = ((TextBox)LoginView.FindControl(«CountyTextBox»)).Text;
}
protected void LoginView_ViewChange(object sender, System.EventArgs e)
{
DisplayProfileProperties();
}
private void DisplayProfileProperties()
{
TextBox FirstNamesTextBox = (TextBox)LoginView.FindControl(«FirstNamesTextBox»);
if (FirstNamesTextBox !=null)
{
((TextBox)LoginView.FindControl(«FirstNamesTextBox»)).Text = Profile.FirstNames;
((TextBox)LoginView.FindControl(«LastnameTextBox»)).Text = Profile.Lastname;
((TextBox)LoginView.FindControl(«FirstLineOfAddressTextBox»)).Text = Profile.FirstLineOfAddress;
((TextBox)LoginView.FindControl(«SecondLineOfAddressTextBox»)).Text = Profile.SecondLineOfAddress;
((TextBox)LoginView.FindControl(«TownOrCityTextBox»)).Text = Profile.TownOrCity;
((TextBox)LoginView.FindControl(«CountyTextBox»)).Text = Profile.County;
((TextBox)LoginView.FindControl(«ContactNumTextBox»)).Text = Profile.ContactNum;
}
}
}

Здравствуйте, начал изучать C# и ООП, соответственно.
Использую для этого VS 2010.
Вот код, в котором возникает ошибка:
Кликните здесь для просмотра всего текста
| C# | ||
|
Скрин, ошибки:
Натыкаюсь на неё уже не впервые, однако не могут понять, в чем проблема.
