ASP.Net Webform | Show progress image on page load
Sometime we need to show loader image before page load on user interface. Here below is the code to implement this.
HTML:
<div>
<asp:Button ID="btnLoad" runat="server" Text="Load Country" OnClick="btnLoad_Click" />
</div>
<div>
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="CountryName" HeaderText="Country Name" />
<asp:BoundField DataField="CountryCode" HeaderText="Country Code" />
</Columns>
</asp:GridView>
<div class="loading" align="center">
Please wait ! Page loading...<br />
<br />
<img src="Images/loader.gif" />
</div>
</div>
CSS:
<style type="text/css">
.modal
{
position: fixed;
top: 0;
left: 0;
background-color: black;
z-index: 99;
opacity: 0.8;
filter: alpha(opacity=80);
-moz-opacity: 0.8;
min-height: 100%;
width: 100%;
}
.loading
{
font-family: Arial;
font-size: 10pt;
border: 5px solid #67CFF5;
width: 200px;
height: 100px;
display: none;
position: fixed;
background-color: White;
z-index: 999;
}
</style>
JS:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function ShowProgress() {
setTimeout(function () {
var modal = $('<div />');
modal.addClass("modal");
$('body').append(modal);
var loading = $(".loading");
loading.show();
var top = Math.max($(window).height() / 2 - loading[0].offsetHeight / 2, 0);
var left = Math.max($(window).width() / 2 - loading[0].offsetWidth / 2, 0);
loading.css({ top: top, left: left });
}, 200);
}
$('form').live("submit", function () {
ShowProgress();
});
</script>
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string script = "$(document).ready(function () { $('[id*=btnLoad]').click(); });";
ClientScript.RegisterStartupScript(this.GetType(), "load", script, true);
}
}
protected void btnLoad_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(5000);
string strConnString = ConfigurationManager.ConnectionStrings["constrDemo"].ConnectionString;
string query = "SELECT * FROM Country";
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds, "Customers");
gvCustomers.DataSource = ds;
gvCustomers.DataBind();
}
}
}
btnLoad.Visible = false;
}
Configuration:
<connectionStrings>
<add name="constrDemo" connectionString="Data Source=servername;Initial Catalog=datbasename;User id =dbusername;password=dbpassword" />
</connectionStrings>
Enjoy !!!
:)