2011-09-04 46 views
0

我不擅長與ADO.NET 所以用下面的代碼,我從互聯網 了,但我得到的錯誤「沒有排位置0」 @標線(*) 即使我可以看到一個值被傳遞使用斷點如何將DataGridView內容複製到數據集?

 DataSet ds = new DataSet(); 
     DataTable dt = new DataTable("ProdFromDGV"); 
     ds.Tables.Add(dt); 
     foreach (DataGridViewColumn col in dataGridView1.Columns) 
     { 
      dt.Columns.Add(col.HeaderText, typeof(string)); 
     } 

     foreach (DataGridViewRow row in dataGridView1.Rows) 
     { 
      foreach (DataGridViewCell cell in row.Cells) 
      { 
       *dt.Rows[row.Index][cell.ColumnIndex] = cell.Value.ToString();* 
      } 
     } 
     dt.WriteXml("table.xml"); 

回答

0

您需要首先創建一個DataRow類型,並將其添加到您的數據表,然後才能開始分配給它。

所以,你的代碼現在是這樣的:

DataSet ds = new DataSet(); 
DataTable dt = new DataTable("ProdFromDGV"); 
ds.Tables.Add(dt); 

foreach (DataGridViewColumn col in dataGridView1.Columns) 
{ 
    dt.Columns.Add(col.HeaderText, typeof(string)); 
} 

foreach (DataGridViewRow row in dataGridView1.Rows) 
{ 
    foreach (DataGridViewCell cell in row.Cells) 
    { 
     // This will not work, but it's something similar to this that you need here... 
     DataRow row = new DataRow(); 
     dt.RowCollecion.Add(row);  

     // Now you can assign to the row.... 
     dt.Rows[row.Index][cell.ColumnIndex] = cell.Value.ToString(); 
    } 
} 

dt.WriteXml("table.xml"); 

希望這有助於一些..

0

//這是行不通的,但它是與此類似,你需要的東西在這裏...

只要改變

DataRow row = new DataRow(); 

到:

DataRow row = dt.NewRow(); 

,它會工作。

相關問題