简体   繁体   English

从datagridview列创建数据列

[英]Create datacolumns from datagridview columns

I have a datagridview with columns that I have created at design time. 我有一个datagridview,其中包含我在设计时创建的列。

I now want to create a datatable with the same columns as in the gridview programatically. 现在,我想以编程方式创建一个与gridview中具有相同列的数据表。

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. 这将引发编译错误:无法将DataGridViewColumn的值转换为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. 我也不能使用datasource属性克隆/复制,因为我是手动设置行。

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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