Sunday, November 1, 2009

C# - Converting DataGridView to DataSet - Windows Forms

public System.Data.DataSet DatagridviewToDataset(DataGridView dgv)
{
System.Data.DataSet ds = new System.Data.DataSet();

//Take the data and structure from the datagridview and return it as a dataset. You can use
//"Imports System.Data" declaration at the top of your project/class and remove the system.data
//from the various parts of this function.

try {
//Add a new table to the dataset
ds.Tables.Add("Main");

//Add the columns
System.Data.DataColumn col = default(System.Data.DataColumn);

//For each colum in the datagridveiw add a new column to your table
foreach (DataGridViewColumn dgvCol in dgv.Columns) {
col = new System.Data.DataColumn(dgvCol.DataPropertyName);
ds.Tables["Main"].Columns.Add(col);
}

//Add the rows from the datagridview
System.Data.DataRow row = default(System.Data.DataRow);
int colcount = dgv.Columns.Count - 1;

for (int i = 0; i <= dgv.Rows.Count - 1; i++) {
row = ds.Tables["Main"].Rows.Add();


foreach (DataGridViewColumn column in dgv.Columns) {
row[column.Index] = dgv.Rows[i].Cells[column.Index].Value;

}
}

return ds;
}
catch (Exception ex) {
//Catch any potential errors and display them to the user
MessageBox.Show("Error Converting from DataGridView " + ex.Message);
return null;
}
}

No comments:

Post a Comment