SqlBulkCopy and ProgressBar in ASP.Net

本文关键字:ASP Net in ProgressBar and SqlBulkCopy | 更新日期: 2023-09-27 18:27:40

实际上,我正在导入Excel文件,并通过SqlBulkCopy将记录保存到DB一切都很顺利。现在,我需要显示一个ProgressBar,同时通过SqlBulkCopy保存数据。

我的代码是:

SBC.WriteToServer(dsExcel);
SBC.SqlRowsCopied += new SqlRowsCopiedEventHandler(OnSqlRowsCopied);
SBC.NotifyAfter = 1;

SqlRowsCopied事件中:

private static void OnSqlRowsCopied(object sender, SqlRowsCopiedEventArgs e)
{
//here i tried calling my progressbar. But I'm unable to call it.                   
}  

SqlBulkCopy and ProgressBar in ASP.Net

我认为您需要在实例化对象之后,在调用WriteToServer方法之前设置该值:

using (SqlConnection conn = new SqlConnection(ConnectionString))
{
    conn.Open();
    using (SqlBulkCopy sqlcpy = new SqlBulkCopy(conn))
    {
        sqlcpy.SqlRowsCopied += new SqlRowsCopiedEventHandler(OnSqlRowsCopied); //<<---- You need to add this here
        sqlcpy.NotifyAfter = 1;
        sqlcpy.BatchSize = batchSize;
        sqlcpy.BulkCopyTimeout = 60;
        using (SqlCommand cmd = new SqlCommand(Sql, conn))
        {
            cmd.ExecuteNonQuery();
            sqlcpy.DestinationTableName = TableName;  //copy the datatable to the sql table
            sqlcpy.WriteToServer(dt);
            return sqlcpy.GetRowsCopied();
        }
    }
}

不用说,但您还需要一个OnSqlRowsCopied事件处理程序:

private static void OnSqlRowsCopied(object sender, SqlRowsCopiedEventArgs e)
{
   Console.WriteLine("Copied {0} so far...", e.RowsCopied);
}