如DataTable已綁定過數據源:
DataTable dt = (dataGridView1.DataSource as DataTable)
remark:使用上面的方法時,把DataGridView的數據賦給沒綁定數據的DataTabe,之后改變DataTable時貌似會改變復制的DataGridView的數據
如DataTable未綁定過數據源:
/// <summary>
/// 綁定DataGridView數據到DataTable
/// </summary>
/// <param name="dgv">復制數據的DataGridView</param>
/// <returns>返回的綁定數據后的DataTable</returns>
public DataTable GetDgvToTable(DataGridView dgv)
{
DataTable dt = new DataTable();
// 列強制轉換
for (int count = 0; count < dgv.Columns.Count; count++)
{
DataColumn dc = new DataColumn(dgv.Columns[count].Name.ToString());
dt.Columns.Add(dc);
}
// 循環行
for (int count = 0; count < dgv.Rows.Count; count++)
{
DataRow dr = dt.NewRow();
for (int countsub = 0; countsub < dgv.Columns.Count; countsub++)
{
dr[countsub] = Convert.ToString(dgv.Rows[count].Cells[countsub].Value);
}
dt.Rows.Add(dr);
}
return dt;
}
參考:http://www.cnblogs.com/linji/archive/2012/10/11/2719471.html
