Rafał Developer
Rafał Developer

Reputation: 2045

An object reference is required for the non-static field, method, or property (dataset)

Why Method can`t send me values from database using dataset?

Here is example

Example with error

public string dane()
        {
            // Get the DataTable of a DataSet.

            DataTable table = DataSet1.Tables["Products"];
            DataRow[] rows = table.Select();

            string s ="";
            // Print the value one column of each DataRow.
            for (int i = 0; i < rows.Length; i++)
            {
                s += rows[i]["ProductID"] + "  ";
            }

            return s;

        }

Error - An object reference is required for the non-static field, method, or property

It`s not possible to find data. (but error is fixed)

public string dane()
{
    // Get the DataTable of a DataSet.
    DataSet1 dataSet = new DataSet1();
    DataTable table = dataSet.Tables["Products"];
    DataRow[] rows = table.Select();

    string s ="";
    // Print the value one column of each DataRow.
    for (int i = 0; i < rows.Length; i++)
    {
        s += rows[i]["ProductID"] + "  ";
    }

    return s;

}

enter image description here

Upvotes: 1

Views: 1996

Answers (2)

tnw
tnw

Reputation: 13877

Thats because your DataSet1 class is probably not static, though we don't know because you haven't shown us. You cannot reference Tables without creating a DataSet1 object first. I imagine you get the error here:

DataTable table = DataSet1.Tables["Products"];

And in your second code example, you actually create an instance of DataSet which resolves the error.

You can either keep your fix or make DataSet1 static, though in this case, it doesn't seem that that would be a good solution.

Upvotes: 3

Kinexus
Kinexus

Reputation: 12904

You have no reference to the dataset in the first example. You need to pass this in or make it a global variable.

Upvotes: 1

Related Questions