C#中点击一个userControl里的导入按钮得到的信息怎样插入到另一个userControl里的gridview中?
这是前后对照图:
点击导入之后是:
对话框可以不要
usercontrol
是在同一个页面吗?
不在同一个页面
@lichen辰: 你可以尝试用一下委托,因为你是在不同的页面,要在A页面操作,响应B页面的事件,这个委托可以解决
//添加按钮
private void btnAdd_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog.ShowDialog();
if (DialogResult.OK == result)
{
string filepath = openFileDialog.FileName;
FileInfo fileInfo = new FileInfo(filepath);
string fileName = fileInfo.Name;
string fileType = fileName.Split('.')[1];
//在表格里添加单元格
DataGridViewRow row = new DataGridViewRow();
row.CreateCells(dataGridView, new string[] { fileName.Split('.')[0], fileType, filepath });
this.dataGridView.Rows.Add(row);
}
}
//删除
private void btnDelete_Click(object sender, EventArgs e)
{
DataGridViewSelectedRowCollection rows = this.dataGridView.SelectedRows;
foreach (DataGridViewRow row in rows)
{
this.dataGridView.Rows.Remove(row);
}
}
//得到导入文件路径
public string[] getFilePath()
{
int dataCount = this.dataGridView.Rows.Count;
if (dataCount > 0)
{
string[] filePaths = new string[dataCount];
//选中行集合
DataGridViewSelectedRowCollection rows=this.dataGridView.SelectedRows;
//获取选中文件路径
for(int i=0;i<rows.Count;i++)
{
filePaths[i] = rows[i].Cells[2].Value.ToString() ;
}
return filePaths;
}
else
{
MessageDialog.ShowWarning("请添加导入文件!");
return null;
}
}
//导入按钮
private void btnImport_Click(object sender, EventArgs e)
{
string[] filepaths = addDataFile.getFilePath();
if (filepaths == null)
return;
try
{
foreach (string filepath in filepaths)
{
string sqlStr = "select * from " + Path.GetFileName(filepath);
dtTable = Tool.readCSVToDataTable(sqlStr,filepath);
dataToDabase(dtTable);
}
}
catch (Exception ex)
{
MessageDialog.ShowError(ex.Message);
}
}
#endregion
//导入数据到数据库
public void dataToDabase(DataTable dtTable)
{
int addCount = dtTable.Rows.Count;
string sqlSelect = "select * from " + talbe;
int deleteCount = DBObject.QueryCount(sqlSelect);
string sqlDeleteStr = "truncate table " + talbe;
DBObject.ExecuteSql(Tool.DB_NAME,sqlDeleteStr);
//添加
DataTableToDataBase(Tool.DB_CONNECT, talbe, dtTable);
DataImportFinish dataImportFinish = new DataImportFinish(addCount, deleteCount);
panel2.Controls.Clear();
panel2.Controls.Add(dataImportFinish);
btnImport.Hide();
btnOver.Visible = true;
}
#region 数据操作
/// <summary>
/// 将读取的数据放入到dataBase中
/// </summary>
/// <param name="connectionStr"></param>
/// <param name="tableName"></param>
/// <param name="dt"></param>
private void DataTableToDataBase(string connectionStr,string tableName,DataTable dt)
{
SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionStr, SqlBulkCopyOptions.UseInternalTransaction);
sqlbulkcopy.DestinationTableName = tableName;//数据库中的表名
sqlbulkcopy.WriteToServer(dt);
}
#endregion