blah blah blah is here! blah blah » Close

up0down
link

Hi,

Is there any way to get the contents of a DataGridView (created programmatic) to a OleDbDataAdapter ? or to a DataSet component?

Thanks

David

last answered one year ago

2 answers

up0down
link

Well, you can certainly transfer the contents of a DGV to a DataSet.

The code would be something like this - I've assumed all DataColumns would be of type string:

DataSet ds = new DataSet("MyDataSet");
DataTable dt = new DataTable("MyTable");

// create columns in datatable
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
DataColumn dc = new DataColumn(column.Name);
dt.Columns.Add(dc);
}

// transfer rows
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.IsNewRow) break;
DataRow dr = dt.NewRow();
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
dr[column.Name] = row.Cells[column.Name].Value;
}
dt.Rows.Add(dr);
}

ds.Tables.Add(dt);

Thank you, but can i do that if i want to populate a OleDbDataAdapter component, and after that to fill a data set using Fill() methode!?

up0down
link

Thank you, but can i do that if i want to populate a OleDbDataAdapter component, and after that to fill a data set using Fill() methode!?

vulpes
17279

Well, you'd need to create an empty table in your database with the same schema as the DGV, 'new up' a DataSet and call OleDbAdapter.Fill() to add a DataTable to that DataSet. Having populated the DataTable from the rows in the DGV, you'd then need to call OleDbAdapter.Update() to write those rows to the database table itself.

Feedback