[英]C# create table from datagrid (only 2 fields)
but cant find any information.但找不到任何信息。 Restricted on time.
限时。
I have a Datagridview, 6 fields.我有一个 Datagridview,6 个字段。
I need to make a Datatable that only contains 2 of those fields.我需要制作一个只包含其中两个字段的数据表。
fields are part and pareto.字段是部分和帕累托。
so I need all the records but only want 2 of the fields in my Datatable.所以我需要所有记录,但只需要我的数据表中的 2 个字段。
Using c sharp .net 4.0 and Microsoft visual studio 2010使用 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);
}
Just add the Cells you want from every row.只需从每一行添加您想要的单元格。 All you need to do is filter the Columns.
您需要做的就是过滤列。
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);
}
Something like this should do it.应该这样做。 Just make sure your DataTable has the appropriate rows.
只需确保您的 DataTable 具有适当的行。
For someone looking for an answer up to date and simple, I may suggest below code:对于寻找最新和简单答案的人,我可能会建议以下代码:
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();
}
}
and, if you need, assign DataTable
to DataGridView
:并且,如果需要,将
DataTable
分配给DataGridView
:
DGV.Rows.Clear();
DGV.ColumnCount = 0;
DGV.DataSource = dt;
now you have a DataBound DataGridView
from an Unbound
DataGridView
in seconds...现在,您可以在几秒钟内从未
Unbound
DataGridView
获得一个DataBound DataGridView
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.