2013-03-09 80 views
0

我在創建datarow對象的位置出現錯誤。嘗試在數據集表中插入新行時出錯

對象引用不設置到對象的實例

protected void Button2_Click(object sender, EventArgs e) 
    { 
     SqlConnection con2 = new SqlConnection("Data Source=AMIT-PC\\SQLEXPRESS;Initial Catalog=Amit;Integrated Security=true"); 
     con2.Open(); 
     SqlCommand cmd2 = new SqlCommand("Select * from hotel.country", con2); 

     SqlDataAdapter da2 = new SqlDataAdapter(cmd2); 
     SqlCommandBuilder sb = new SqlCommandBuilder(da2); 
     DataSet ds2 = new DataSet(); 
     da2.Fill(ds2); 
     /* GridView2.DataSource = ds2; 
     GridView2.DataBind();*/ 

     DataRow dr = ds2.Tables["hotel.country"].NewRow(); 
     dr[ds2.Tables[TextBox1.Text].Columns[0].ColumnName] = TextBox2.Text; 
     dr[ds2.Tables[TextBox1.Text].Columns[1].ColumnName] = TextBox3.Text; 
     da2.Update(ds2); 
     GridView1.DataBind(); 

    } 
+0

我不知道爲什麼,誰只是評論的傢伙刪除他的帖子,因爲它解決了我的問題......那是我不能在ds2.Tables [「」]中使用表名,而應該使用數字。 – 2013-03-09 10:52:48

+0

刪除它,因爲我有關於存儲過程的一些信息,並且您正在使用select命令。我現在改變了我的答案。 – JodyT 2013-03-09 10:56:51

+0

如果你將有超過5張桌子,你會記得所有的數字嗎?嘗試'DataRow dr = ds2.Tables [「country」]。NewRow()' 如果您使用table Country等創建了像DsHotel一樣的自己的數據集,那麼它會容易得多。那麼它將是 'DsHotel.CountryRow dr = DsHotel.Country.NewRow(); dr.YourColumnName = ....' – 2013-03-09 11:05:33

回答

0

您就可以創建一個映射:

da2.TableMappings.Add("Table", "Hotel.Country"); 

或者通過訪問它:

ds2.Tables[0].NewRow(); 

編輯:

如果你想使用表名,這可能會更容易。

da2.Fill(ds2, "Hotel.Country"); 
+0

感謝朋友的幫助 – 2013-03-09 11:05:41

0

試試這個...

DataRow dr = ds2.Tables[0].NewRow(); 
    dr[ds2.Tables[TextBox1.Text].Columns[0].ColumnName] = TextBox2.Text; 
    dr[ds2.Tables[TextBox1.Text].Columns[1].ColumnName] = TextBox3.Text; 
    da2.Update(ds2); 

可能這可以幫助你....

+0

感謝sagar問題解決 – 2013-03-09 11:04:41

相關問題