简体   繁体   中英

How to add grid view values to datatable using for loops

here is the error how to add bunch of grid view values to datatable using for loops this is my code it does not worked.

for(int r=0; r<dataGridView1.Columns.Count; r++)
        {
            Dtbl.Columns.Add();
        }
        //Dtbl.Columns.Add("1");
        //Dtbl.Columns.Add("2");
        //Dtbl.Columns.Add("3");
        //Dtbl.Columns.Add("4");
        //Dtbl.Columns.Add("5");
        //Dtbl.Columns.Add("6");
        //Dtbl.Columns.Add("7");

        for (int x = 0; x < dataGridView1.Rows.Count; x++)
        {
            for(int y =0; y<dataGridView1.Columns.Count; y++)
            {
              Dtbl.Rows[x].ItemArray[y] =  dataGridView1.Rows[x].Cells[y].Value;    //Dtbl.Rows.Add(dataGridView1.Rows[x].Cells[y].Value);
            }
        }

Try this simple way.

    DataTable dt = new DataTable();

    //add as many columns you want.
    dt.Columns.Add("YOUR COLUMN NAME");

    foreach (GridViewRow row in gv.Rows)
    {
         DataRow dr;
         dr = dt.NewRow();
         //dr["xxx"] => replace 'xxx' with respective key for all dr.
         dr["date"] = DateTime.Parse(row.Cells[0].Text);
         //adding records to datatable one by one.
         dt.Rows.Add(dr);
     }

Alternative, to this:

DataTable GetDataTable(GridView dtg)
        {
            DataTable dt = new DataTable();

            // add the columns to the datatable            
            if (dtg.HeaderRow != null)
            {

                for (int i = 0; i < dtg.HeaderRow.Cells.Count; i++)
                {
                    dt.Columns.Add(dtg.HeaderRow.Cells[i].Text);
                }
            }

            //  add each of the data rows to the table
            foreach (GridViewRow row in dtg.Rows)
            {
                DataRow dr;
                dr = dt.NewRow();

                for (int i = 0; i < row.Cells.Count; i++)
                {
                    dr[i] = row.Cells[i].Text.Replace(" ", "");
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }

avoiding for-loops:-

BindingSource bs = (BindingSource)dgrid.DataSource;
DataTable dt= (DataTable) bs.DataSource;

should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM