简体   繁体   中英

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;

}

在此输入图像描述

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM