An object reference is required for the nonstatic field, method, or property

  • Thread starter Vicky via DotNetMonster.com
  • Start date
V

Vicky via DotNetMonster.com

Hi, I need help with "An object reference is required for the nonstatic
field, method, or property 'dataReader.Class1.data'"
Before I put folowing variable in class level, it works fine.
------------------
string[] data;
string valTicker = "";
string valPeriod = "";
---------------------

but after put them into class level I got above error msg.
I did to put
dataReader.Class1.valTicker = data[0];
it still not work.
PLease help with any info.
Thank you very much!

please see code blow.

-----------------------------------------------------------------------
using System;

using System.Data;

using System.Data.SqlClient;

using System.IO;

namespace dataReader

{

/// <summary>

/// Summary description for Class1.

/// </summary>

class Class1

{

int FundID = 0;

string[] data;

string valTicker = "";

string valPeriod = "";

[STAThread]

public static void Main(string[] args)

{

StreamReader sr = new StreamReader("C:\\Vicky Development\\FundExplorer\\
Index\\Copy of IntlIndex\\TestA1DOWM.txt");

string currentLine = null;

string myConnString= "workstation id=HIRST-IT1;packet size=4096;"+

"Integrated Security=SSPI;initial catalog=FundManager42205;"+ "Data
Source=HIRST-IT1\\TEST;"+

"persist security info=True";

//read the text file

currentLine = sr.ReadLine();

currentLine = sr.ReadLine();

if(currentLine != null)

{


//string[] data = currentLine.Split(',');

data = currentLine.Split(',');

//string valTicker = data[0];

//valTicker = data[0];

valTicker = data[0];

//string valPeriod = data[1];

valPeriod = data[1];


string valDate = data[2];

string valNavCl = data[6];


Console.WriteLine(valTicker);

Console.WriteLine(valPeriod);

Console.WriteLine(valDate);

Console.WriteLine(valNavCl);


//string mySelectQuery = "SELECT FundID,Ticker, PeriodicityID FROM
Information3 WHERE (Ticker = '.A1DOW')AND (PeriodicityID = 4)";

string mySelectQuery = "SELECT FundID,Ticker, PeriodicityID FROM
Information3 WHERE Ticker = '" + valTicker + "'" + " AND PeriodicityID = 4";

SqlConnection cnn = new SqlConnection(myConnString);

SqlCommand cmd = new SqlCommand(mySelectQuery,cnn);

cnn.Open();

SqlDataReader myReader = null;

cmd.CommandText = mySelectQuery;

cmd.CommandType = CommandType.Text;



myReader= cmd.ExecuteReader();


for (int i=0; i < myReader.FieldCount; i++)

{

Console.Write("{0}", myReader.GetName(i).PadLeft(20, ' '));

}

Console.WriteLine("\n{0}", "".PadLeft(60, '-'));

//int FundID=0;

int PeriodicityID=0;;

string Ticker=null;



myReader.Read();

if (myReader.HasRows ==true)

{

int FundID = myReader.GetInt32(0);

Ticker = (string)myReader["Ticker"];

PeriodicityID = myReader.GetInt32(2);



Console.WriteLine("{0}{1}{2}",

FundID.ToString().PadLeft(20,' '),

Ticker.ToString().PadLeft(20, ' '),

PeriodicityID.ToString().PadLeft(20, ' '));



//***************************************************

cnn.Close();

myConnString= "workstation id=HIRST-IT1;packet size=4096;"+

"Integrated Security=SSPI;initial catalog=FundManager42205;"+ "Data
Source=HIRST-IT1\\TEST;"+

"persist security info=True";

cnn = new SqlConnection(myConnString);

cnn.Open();

// Start a local transaction.

SqlTransaction myTrans = cnn.BeginTransaction();

// Enlist the command in the current transaction.

SqlCommand myCommand = cnn.CreateCommand();

//SqlCommand myCommand = new SqlCommand(mySelectQuery,cnn);

myCommand.Transaction = myTrans;



try

{

mySelectQuery = "DELETE FROM Performance WHERE FundID =" + FundID ;

myCommand.CommandText = mySelectQuery;

myCommand.ExecuteNonQuery();


//insert

myCommand.CommandText = "Insert into Performance (FUNDID, FUNDDATE,[RETURN]
,NAV,FINAL,SOURCE,Periodicity)"+

"VALUES (20222, '" + valDate + "'" +",0.6012,'" + valNavCl + "'"
+",1,'Returs','month')";


myCommand.ExecuteNonQuery();

myTrans.Commit();

Console.WriteLine("records are deleted & updated in database.");

}

catch(Exception e)

{

try

{

myTrans.Rollback();

}

catch (SqlException ex)

{

if (myTrans.Connection != null)

{

Console.WriteLine("An exception of type " + ex.GetType() +

" was encountered while attempting to roll back the transaction.");

}

}

Console.WriteLine("An exception of type " + e.GetType() +

"was encountered while inserting the data.");

Console.WriteLine("Neither record was deleted to database.");

}

finally

{

cnn.Close();

}


}

// always call Close when done reading.

myReader.Close();

// Close the connection when done with it.

cnn.Close();


Console.ReadLine(); //to be sure your window will not close immediately



currentLine = sr.ReadLine();



} //end if hasrows


}//end of if(currentLine != null)


}

}
 
A

Angrez Singh

Hi,

Because data, valTicker are not static members of class so you have to
access them via object of Class1 . The main method inside the Class1 is
just for the entry point of the application.

Regards,
Angrez
 
V

Vicky via DotNetMonster.com

Angrez,

Thanks for the reply.
I will put part of the code into a method and test again.
but I am not sure what should stay in main method.

Vicky
 
M

Morten Wennevik

Hi Vicky,

The error is caused by the fact that when you put them as class variables, they will need an instance of the class to be accessed. The Main method is static and doesn't belong to any particular instance and will therefore not be able to use non-static methods or variables.

There are several ways to solve this.
1) Put the variables inside the Main method.

public static void Main(string[] args)
{
string[] data;
string valTicker = "";
string valPeriod = "";

// rest of the code
}


2) Make the variables static

static string[] data;
static string valTicker = "";
static string valPeriod = "";

3) Create an instance of a class from Main and put your code inside a method of that instance.

This is the way you should do it

public static void Main(string[] args)
{
Class1 refToClass = new Class1();
refToClass.DoSomeWork();
}

private void DoSomeWork()
{
// code that you used to have in Main
}
 
V

Vicky via DotNetMonster.com

Morten,

Thank you so much for your help, I will test it.
Thanks!

Vicky
 
V

Vicky via DotNetMonster.com

Thanks all, it is working like a champ.
Now I have a question of sql
below code works,
------------------------------------------------------------------
mySelectQuery = "Insert into Performance4 (FUNDID, FUNDDATE,[RETURN]
,NAV,FINAL,SOURCE,Periodicity)"+

"VALUES (20222, '" + valDate + "'" +",0.6012," + valNavCl
+",1,'Returs','month')";

myCommand.CommandText = mySelectQuery;
------------------------------------------------------------------
but when I replace 20222 with FundID which is an int variable, and did a
addWatch,
it still display FundID, instead number.
could anyone let me know what is the right syntax?

mySelectQuery = "Insert into Performance4 (FUNDID, FUNDDATE,[RETURN]
,NAV,FINAL,SOURCE,Periodicity)"+

"VALUES (FundID, '" + valDate + "'" +",0.6012," + valNavCl
+",1,'Returs','month')";
 
M

Morten Wennevik

When dealing with Sql, you should use SqlParameter for each value. SqlParameters are easier to maintain and can perform conversions to Sql data types not found in .Net (like money).

string mySelectQuery = @"Insert into Performance4 (
FUNDID,
FUNDDATE,
[RETURN],
NAV,
FINAL,
SOURCE,
Periodicity)
VALUES (
@FUNDID,
@FUNDDATE,
@RETURN,
@NAV,
@FINAL,
@SOURCE,
@Periodicity)";

SqlCommand mySelectCommand = new SqlCommand(mySelectQuery);
mySelectCommand.Parameters.Add(new SqlParameter("@FUNDID", SqlDbType.Int, FundID));
mySelectCommand.Parameters.Add(new SqlParameter("@FUNDDATE", SqlDbType.?, valDate));
mySelectCommand.Parameters.Add(new SqlParameter("@RETURN", SqlDbType.?, 0.6012, ParameterDirection.ReturnValue));
....
and so on

the @ in mySelectQuery allows for a continuous string spanning several lines
All parameter variables need to be prefixed by @, but can otherwise be named anything you like.
For SqlDb queries you don't really need to add the parameters in any specific order, but good practice is to follow the order of the query string. OleDB queries do not support named parameters so in those cases you HAVE TO add the parameters in the correct order.

For sql questions in general microsoft.public.dotnet.framework.adonet is your friend.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top