简体   繁体   中英

NullReference Exception was unhandles

I'm having trouble when adding new team to the dataTable. VisualStudio is pointing at line teams.Rows.Add(dr) with NullReference error. Can you please help me?

        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)
    {

The DataTable is not yet initialized

static DataTable teams;

You can initilaize it for example with the default constructor :

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

Although it's not clear why you made them static. This would mean that every instance of Program would share the same DataTable which can be problematic with multiple threads since you need to provide a locking mechanism. Just remove the static and create an instance of Program :

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

Edit : There's something else wrong. You're creating the new DataRow via players.NewRow but adding it to the DataTable teams . That is not allowed. Every DataRow belongs to one DataTable. That cannot be changed and will result in an ArgumentException .

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

so add it to players instead:

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

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