我想從GridGridView的DataGridView中獲取DataTable。如何在沒有任何數據源的情況下從DataGridView製作DataTable?
換句話說數據表一樣的DataGridView值
我想從GridGridView的DataGridView中獲取DataTable。如何在沒有任何數據源的情況下從DataGridView製作DataTable?
換句話說數據表一樣的DataGridView值
可能是一個更好的方式來做到這一點,但否則它會通過DGV相當瑣碎,只是環和手動創建數據表。
像這樣的東西可能會奏效:
DataTable dt = new DataTable();
foreach(DataGridViewColumn col in dgv.Columns)
{
dt.Columns.Add(col.Name);
}
foreach(DataGridViewRow row in dgv.Rows)
{
DataRow dRow = dt.NewRow();
foreach(DataGridViewCell cell in row.Cells)
{
dRow[cell.ColumnIndex] = cell.Value;
}
dt.Rows.Add(dRow);
}
您可以從DataGridView中投的DataSource對象到DataTable
DataTable dt = new DataTable();
dt = (DataTable)dataGridView1.DataSource;
應該指出的是,如果DataSource是BindingList
您可以使用下面的代碼也,這個代碼填不影響你的DataGridView當你做一些添加或刪除數據表中的行時
DataTable dt = new DataTable();
dt = Ctype(dataGridView1.DataSource,DataTable).copy();
難道你不能實例化吃了一個新的數據表並將其設置爲gridview的數據源? – Flynn1179 2010-06-24 10:32:48