我尝试使用以下代码复制数据表:
private void button1_Click(object sender, EventArgs e)
{
DataTable dat = dGV.DataSource as DataTable;
DataTable dt = new DataTable();
dt = dat.Copy();
dGV.DataSource = dt;
}
但是当我运行它时,第一行没有被复制。结果如下:
之前:https://drive.google.com/file/d/0B--Fi4mWsFk5NXlJM0ZRSXhRbjA/view?usp=sharing
之后:https://drive.google.com/file/d/0B--Fi4mWsFk5OFptY2ZPRHlNaWc/view?usp=sharing
如果在单击按钮之前将光标移动到第二行,它将复制包括第一行在内的所有数据。使用以下代码从excel导入数据:
private void importFileDialog_FileOk(object sender, CancelEventArgs e)
{
dGV.DataSource = GetTable();
string path = importFileDialog.FileName;
string ext = Path.GetExtension(path);
if (ext == ".xlsx" | ext == ".xls")
{
try
{
string Excel03ConString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;";
string Excel07ConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0;";
string conStr, sheetName;
conStr = string.Empty;
switch (ext)
{
case ".xls": //Excel 97-03
conStr = string.Format(Excel03ConString, path);
break;
case ".xlsx": //Excel 07
conStr = string.Format(Excel07ConString, path);
break;
}
//Get the name of the First Sheet.
using (OleDbConnection con = new OleDbConnection(conStr))
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
con.Open();
DataTable dtExcelSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
con.Close();
}
}
//Read Data from the First Sheet.
using (OleDbConnection con = new OleDbConnection(conStr))
{
using (OleDbCommand cmd = new OleDbCommand())
{
using (OleDbDataAdapter oda = new OleDbDataAdapter())
{
DataTable dt = new DataTable();
cmd.CommandText = "SELECT * From [" + sheetName + "]";
cmd.Connection = con;
con.Open();
oda.SelectCommand = cmd;
oda.Fill(dt);
con.Close();
//Populate DataGridView.
//dGV.DataSource = dt;
for (int i = 0; i < dt.Rows.Count; ++i)
{
//dGV.RowCount++;
//dGV.Rows[i].HeaderCell.Value = dt.Row[i].;
for (int k = 0; k < dt.Columns.Count; ++k)
{
dGV[k, i].Value = dt.Rows[i].ItemArray[k];
}
}
}
}
}
}
catch
{
MessageBox.Show("Failed to read the file");
}
}
}
如果我手动输入数据,一切正常。
答案 0 :(得分:1)
您也可以使用clone function
试试此
private void button1_Click(object sender, EventArgs e)
{
DataTable dat = (DataTable)dGV.DataSource;
DataTable dt = new DataTable();
dt = dat.Clone();
dGV.DataSource = dt;
}
或
DataTable dt = (DataTable)dGV.DataSource;
dGV.DataSource = dt;