在 C# 错误 (Visual Studio) 中向 table 添加行

Add row to table in C# error (Visual Studio)

我对这些代码有疑问。我想向数据集添加一行,但对于 sampleDataSet.bar_of_4Row,出现此错误“非静态字段、方法或 属性 需要对象引用”。我试图将其设为静态,但没有用。我试着像本教程中那样做:https://msdn.microsoft.com/en-us/library/5ycd1034.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NaplnenieDB
{
    class Program
    {

        static void Main(string[] args)
        {

            sampleDataSet.bar_of_4Row newBarRow = sampleDataSet.bar_of_4.Newbar_of_4Row();
            newBarRow.bar = "RRRR";
            newBarRow.first = "R";
            sampleDataSet.bar_of_4.Addbar_of_4Row(newBarRow);



        }


    }
}

您需要创建 class sampleDataSet.bar_of_4 的对象,以便在其上调用方法 Newbar_of_4Row()

试试这个:

var myDataSet= new sampleDataSet();
sampleDataSet.bar_of_4Row newBarRow = myDataSet.bar_of_4.Newbar_of_4Row();
newBarRow.bar = "RRRR";
newBarRow.first = "R";
myDataSet.bar_of_4.Addbar_of_4Row(newBarRow);

尽量遵守 class 名称以大写字母开头,变量名以小写字母开头的约定。这将使这一切不那么混乱。

这将创建一个新的 DataTable、DataRow(s)、DataColumn(s) 并允许您填充值。

希望对您有所帮助。

static void Main(string[] args)
    {

        // create table 
        DataTable sampleDataTable = new DataTable("Bar_of_4");
        // create row
        DataRow sampleDataRow = sampleDataTable.NewRow();
        // create column
        DataColumn column;

        // set info about the first column
        column = new DataColumn();
        column.DataType = System.Type.GetType("System.String");
        column.ColumnName = "bar";
        sampleDataTable.Columns.Add(column);

        // set info about the second column
        column = new DataColumn();
        column.DataType = System.Type.GetType("System.String");
        column.ColumnName = "first";
        sampleDataTable.Columns.Add(column);

        // add column data to the first row
        sampleDataRow["bar"] = "RRRR";
        sampleDataRow["first"] = "R";
        sampleDataTable.Rows.Add(sampleDataRow);

        // add column data to the second row
        sampleDataRow = sampleDataTable.NewRow();
        sampleDataRow["bar"] = "SSSS";
        sampleDataRow["first"] = "S";
        sampleDataTable.Rows.Add(sampleDataRow);


        // loop through each row and display the column info
        foreach (DataRow row in sampleDataTable.Rows)
        {
            Console.WriteLine(string.Format("{0} - {1}",row["bar"],row["first"]));
        }

        Console.WriteLine("\n\nPress any key to continue");
        Console.ReadKey();
    }