繁体   English   中英

C# 从数据网格创建表(只有 2 个字段)

[英]C# create table from datagrid (only 2 fields)

但找不到任何信息。 限时。

我有一个 Datagridview,6 个字段。

我需要制作一个只包含其中两个字段的数据表。

字段是部分和帕累托。

所以我需要所有记录,但只需要我的数据表中的 2 个字段。

使用 c sharp .net 4.0 和 Microsoft visual studio 2010

DataGridViewRowCollection coll = dataGridView1.Rows; 

DataTable t = new DataTable(); 

t.Columns.Add(); 

foreach (DataGridViewRow item in coll) 

{
     t.Rows.Add(item.Cells[0].Value);
}

只需从每一行添加您想要的单元格。 您需要做的就是过滤列。

foreach( DataGridViewRow row in myDataGridView.Rows)
{
      DataRow tableRow = myDataTable.NewRow();
      tableRow.Cells["part"].value = row["part"].value;
      tableRow.Cells["pareto"].value = row["pareto"].value;
      myDataTable.Rows.Add(tableRow);
}

应该这样做。 只需确保您的 DataTable 具有适当的行。

对于寻找最新和简单答案的人,我可能会建议以下代码:

DataTable dt = new DataTable();
foreach (DataGridViewColumn column in DGV.Columns)
{
    dt.Columns.Add(column.HeaderText, (column.ValueType == null ? typeof(string) : column.ValueType));
}
foreach (DataGridViewRow row in DGV.Rows)
{
    dt.Rows.Add();
    foreach (DataGridViewCell cell in row.Cells)
    {
        dt.Rows[dt.Rows.Count - 1][cell.ColumnIndex] = cell.Value == null ? "" : cell.Value.ToString();
    }
}

并且,如果需要,将DataTable分配给DataGridView

DGV.Rows.Clear();
DGV.ColumnCount = 0;
DGV.DataSource = dt;

现在,您可以在几秒钟内从未Unbound DataGridView获得一个DataBound DataGridView ...

暂无
暂无

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

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