繁体   English   中英

NullReference Exception是unhandles

[英]NullReference Exception was unhandles

我在向dataTable添加新团队时遇到了麻烦。 VisualStudio指向具有NullReference错误的line teams.Rows.Add(dr)。 你能帮我么?

        private void addTeam(String nazwa)
    {

        DataRow dr = players.NewRow();
        //dr["playerID"] = nazwa;

        dr["nazwa"] = nazwa;
        teams.Rows.Add(dr); //<--there is en error
    }


class Program
{
    static DataTable players ;
    static DataTable teams;
    private DataSet teamMenager;

    static void Main(string[] args)
    {

DataTable尚未初始化

static DataTable teams;

例如,您可以使用默认构造函数初始化它:

static DataTable teams = new DataTable();
static DataTable players = new DataTable();

虽然不清楚为什么你让它们变得静止。 这意味着,每一个实例Program将共享相同的DataTable ,因为你需要提供的锁定机构可与多线程问题。 只需删除静态并创建一个Program实例:

static void Main(string[] args)
{ 
    Program p = new Program();
    p.Start(); // open your form(s) there and add teams or what else
    // ...

编辑 :还有其他错误。 您正在通过players.NewRow创建新的DataRow ,但将其添加到DataTable teams 这是不允许的。 每个DataRow都属于一个DataTable。 这是无法更改的,并将导致ArgumentException

DataRow dr = players.NewRow();
dr["nazwa"] = nazwa;

所以把它添加到玩家:

players.Rows.Add(dr); //<--there is en error

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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