2013-05-15 53 views
0

我遇到了一個奇怪的錯誤:怪異的NullReferenceException錯誤

mycon.Open(); 

adap = new SqlDataAdapter("SELECT * FROM Employee; Select * from Shift; select * from Has_Shift", mycon); 
adap.TableMappings.Add("T1", "Employee"); 
adap.TableMappings.Add("T2", "Shift"); 
adap.TableMappings.Add("T3", "Has_Shift"); 

adap.Fill(ds); 

DataRow newRow = ds.Tables["T1"].NewRow(); 
newRow["Name"] = textBox1.Text; 
ds.Tables["T1"].Rows.Add(newRow); 
adap.Update(ds); 
mycon.Close(); 

有一個錯誤指出:

Object reference not set to an instance of an object at the DataRow newRow line.

我不知道爲什麼會發生。

+0

你在哪裏初始化'ds'? –

+0

@JeremyTodd,'adap.Fill(ds);' – Habib

+0

這不會初始化數據集,它只是用數據填充它(儘管如果'ds'爲空,我希望它會拋出異常)。 –

回答

0

If you use a batch SQL statement to retrieve multiple tables and fill a DataSet, the first table is named using the table name specified to the Fill method. Subsequent tables are named using the name specified to the Fill method plus a number starting from one and incrementing by one. For example, if you were to run the following code: MSDN

因此,代碼將

adap = new SqlDataAdapter("SELECT * FROM Employee; Select * from Shift; select * from Has_Shift", mycon); 

// second table name will be Employee +1 
adap.TableMappings.Add("Employee1", "Shift"); 
// second table name will be Employee +2 
adap.TableMappings.Add("Employee2", "Has_Shift"); 

// give Table name as below 
adap.Fill(ds, "Employee"); 

DataRow newRow = ds.Tables["Employee"].NewRow(); 
newRow["Name"] = textBox1.Text; 
ds.Tables["Employee"].Rows.Add(newRow); 
adap.Update(ds); 
mycon.Close(); 

因爲我們在這裏填寫方法得到"Employee"作爲表名,第一臺會"Employee"和第二會"Employee1"和第三會「和Employee2」

既然你沒有給出任何表名,你的表名將是「表」,「表1」,「表2」... ... 你可以將它們映射到正確的名稱

adap.TableMappings.Add("Table", "Employee"); 
adap.TableMappings.Add("Table1", "Shift"); 
adap.TableMappings.Add("Table2", "Has_Shift"); 

和代碼的其餘部分將是

adap.Fill(ds); 

DataRow newRow = ds.Tables["Employee"].NewRow(); 
newRow["Name"] = textBox1.Text; 
ds.Tables["Employee"].Rows.Add(newRow); 
adap.Update(ds); 
mycon.Close();