简体   繁体   中英

Create datacolumns from datagridview columns

I have a datagridview with columns that I have created at design time.

I now want to create a datatable with the same columns as in the gridview programatically.

I tried the following code.

Dim dataTable As New DataTable
For Each col As DataGridViewColumn In dgDocEntries.Columns
   dataTable.Columns.Add(col)
Next

This throws a compile error: value of DataGridViewColumn cannot be converted to DataColumn. Obviously I tried casting the types but it didn't work.

I can't use the datasource property to clone/copy either because I am setting the rows manually.

Something along these lines could do the job:

void CopyTableColumnsFromDGV(DataGridView dgv, DataTable dt)
{
    foreach (DataGridViewColumn dgvCol in dgv.Columns)
    {
        DataColumn dtCol = new DataColumn(dgvCol.Name, dgvCol.ValueType);
        dtCol.Caption = dgvCol.HeaderText;

        dt.Columns.Add(dtCol);
    }
}

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