简体   繁体   中英

NullReference Exception was unhandled in foreach

An unhandled exception of type 'System.NullReferenceException' occurred in MyProject.exe
Additional information: Object reference not set to an instance of an object.

It says , StringCollection strCol is null, but table.Script() is not null (it includes the record). It does the foreach only once. When it comes for a second time it gives this exception. Here is my code:

foreach (var item in Sourceclb.Items)  
{
    Table table = database.Tables[item.ToString()];
    StringCollection strCol = table.Script();//Gives exception here
    var script = "";
    foreach (var key in strCol)
    {
         script += key;
    }
    command.Connection = ttbl;
    command.CommandText = "USE "+_hedefDb+" \n EXEC sp_sqlexec '"+scriptdondur(script)+ "'";

    command.ExecuteNonQuery();
    txtLog.AppendText("*TABLE COPIED* "+item.ToString()+" has been copied. \r\n");
}

I think you need to do

foreach (var item in database.Tables)

rather than

foreach (var item in Sourceclb.Items)

Not all the items in Sourceclb.Items will be tables, and as soon as you hit one that isn't, database.Tables[item.ToString()] will return null, with the consequent NullReferenceException at table.Script() .

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