簡體   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