开发者

How to copy DataGridView contents to Dataset?

开发者 https://www.devze.com 2023-04-02 15:19 出处:网络
i\'m not good with ADO.NET so used the following code that i got from Internet but i get the error \"There is no row at position 0.\" @ the marked line(*)

i'm not good with ADO.NET so used the following code that i got from Internet but i get the error "There is no row at position 0." @ the marked line(*) even though i can see a value is being passed using breakpoints

        DataSet ds = new DataSet();
        DataTable dt = new DataTable("ProdFromDGV");
        ds.Tables.Add(dt);
        foreach (DataGridViewColumn col开发者_Go百科 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");


You need to first create a DataRow type and add it into your DataTable before you can start assigning to it.

So your code will now be something like:

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");

Hope this helps some..


// This will not work, but it's something similar to this that you need here...

Just change

 DataRow row = new DataRow();

to:

DataRow row = dt.NewRow();

and it will work.

0

精彩评论

暂无评论...
验证码 换一张
取 消