2009年6月11日 星期四

進度條

進度條
在處理檔案或資料時,如果處理時間過長導致使用者無法等待時,
常常會需要將處理資料的動作改為背景作業,以便使用者進行其他事項。

以下是進行背景作業時產生進度條的做法(資源來自這裡)

功能頁 (要執行資料處理的那頁)

private void btnHistory_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
System.Threading.Thread thread=new System.Threading.Thread(new System.Threading.ThreadStart(LongTask));
thread.Start();

Session["State"]=1;
OpenProgressBar(this.Page);
}

private void LongTask()
{
//模擬長時間任務
//每個循環模擬任務進行到不同的階段
for(int i=0;i<101;i++)
{
System.Threading.Thread.Sleep(1000);
//設置每個階段的state值,用來顯示當前的進度
Session["State"] = i+1;
}
//任務結束
Session["State"] = 1000;

}

public static void OpenProgressBar(System.Web.UI.Page Page)
{
StringBuilder sbScript = new StringBuilder();

sbScript.Append("<script language='JavaScript' type='text/javascript'>\n");
sbScript.Append("<!--\n");

//IE5.5以下使用window.open
sbScript.Append("window.open('Progress.aspx','', 'height=100, width=350, toolbar =no, menubar=no, scrollbars=no, resizable=no, location=no, status=no');\n");
sbScript.Append("// -->\n");
sbScript.Append("</script>\n");

Page.RegisterClientScriptBlock("OpenProgressBar", sbScript.ToString());

}



進度表(Progress.aspx)

<%@ Page language="c#" Codebehind="Progress.aspx.cs" AutoEventWireup="false" Inherits="Approve.Progress" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>

<title>Progress</title>
<base target="_self">

</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<asp:Label id="lblMessages" runat="server"></asp:Label> <asp:Panel id="panelBarSide" runat="server" Width="300px" BorderStyle="Solid" BorderWidth="1px" ForeColor="Silver"> <asp:Panel id="panelProgress" runat="server" Width="10px" BackColor="Green"></asp:Panel> </asp:Panel> <asp:Label id="lblPercent" runat="server" ForeColor="Blue"></asp:Label>
</form>
</body>
</HTML>

進度表(Progress.aspx.cs)

protected System.Web.UI.WebControls.Label lblMessages;
protected System.Web.UI.WebControls.Panel panelProgress;
protected System.Web.UI.WebControls.Panel panelBarSide;
protected System.Web.UI.WebControls.Label lblPercent;

private int state = 0;
private void Page_Load(object sender, System.EventArgs e)
{
// 在這裡放置使用者程式碼以初始化網頁 // Put user code to initialize the page here
if(Session["State"]!=null)
{
state = Convert.ToInt32(Session["State"].ToString());
}
else
{
Session["State"]=0;
}
if(state>0&&state<=100)
{
this.lblMessages.Text = "Task undertaking!";
this.panelProgress.Width = state*3;
this.lblPercent.Text = state + "%";
Page.RegisterStartupScript("","<script>window.setTimeout('window.Form1.submit()',100);</script>");
}
if(state==1000)
{
this.panelProgress.Visible = false;
this.panelBarSide.Visible = false;
this.lblMessages.Text = "Task Completed!";
Page.RegisterStartupScript("","<script>window.close();</script>");
}
}

沒有留言: