I add rows datagridview one by one in button_click event, i add with :
Dgv.Rows.Add()
Now i need convert Dgv to datatable without loop, is it possible?
I using vb.net in visual studio 2012,
Thanks
CodePudding user response:
Use a DataTable to populate your DGV, then it's easy to retrieve the data into a new DataTable as you need.
Example:
DataTable dataTable = new DataTable();
dataTable.Columns.Add("id");
dataTable.Columns.Add("Name");
dataTable.Columns.Add("address");
dataTable.Columns.Add("phone");
DataRow row = dataTable.NewRow();
row["id"] = 1;
row["name"] = "test1";
row["address"] = "a";
row["phone"] = 1;
dataTable.Rows.Add(row);
dataGridView1.DataSource = dataTable;
To retrieve the data, changed or not, from the grid:
DataTable dataTableDGV = (DataTable)dataGridView1.DataSource;
CodePudding user response:
there! You can try this:
Private Sub SurroundingSub()
Dim dt As DataTable = New DataTable()
For Each col As DataGridViewColumn In dgv.Columns
dt.Columns.Add(col.Name)
Next
For Each row As DataGridViewRow In dgv.Rows
Dim dRow As DataRow = dt.NewRow()
For Each cell As DataGridViewCell In row.Cells
dRow(cell.ColumnIndex) = cell.Value
Next
dt.Rows.Add(dRow)
Next
End Sub