RealSteel
RealSteel

Reputation: 1941

SqlBulkCopy and ProgressBar in ASP.Net

Actually, I am importing Excel file and saving records to DB through SqlBulkCopy and everything goes fine. Now,I need to show a ProgressBar while saving data through SqlBulkCopy.

My Code is :

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

and in the SqlRowsCopied event :

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

Upvotes: 1

Views: 2680

Answers (1)

Mark Kram
Mark Kram

Reputation: 5832

I think you need to set that value right after you instantiate the object and before you call the WriteToServer Method:

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();
        }
    }
}

and it goes without saying but you also need a OnSqlRowsCopied event handler:

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

Upvotes: 1

Related Questions