[英]NullReference Exception was unhandles
I'm having trouble when adding new team to the dataTable. 我在向dataTable添加新团队时遇到了麻烦。 VisualStudio is pointing at line teams.Rows.Add(dr) with NullReference error. VisualStudio指向具有NullReference错误的line teams.Rows.Add(dr)。 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 DataTable
尚未初始化
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. 这意味着,每一个实例Program
将共享相同的DataTable
,因为你需要提供的锁定机构可与多线程问题。 Just remove the static and create an instance of Program
: 只需删除静态并创建一个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
. 您正在通过players.NewRow
创建新的DataRow
,但将其添加到DataTable teams
。 That is not allowed. 这是不允许的。 Every DataRow belongs to one DataTable. 每个DataRow都属于一个DataTable。 That cannot be changed and will result in an ArgumentException
. 这是无法更改的,并将导致ArgumentException
。
DataRow dr = players.NewRow();
dr["nazwa"] = nazwa;
so add it to players instead: 所以把它添加到玩家:
players.Rows.Add(dr); //<--there is en error
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.