简体   繁体   中英

C# create table from datagrid (only 2 fields)

but cant find any information. Restricted on time.

I have a Datagridview, 6 fields.

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.

Using c sharp .net 4.0 and 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.

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 :

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

now you have a DataBound DataGridView from an Unbound DataGridView in seconds...

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