2014-03-12 35 views
0

我有一個web應用程序(不是窗體),用戶從列表框(選擇框)中選擇項目,然後按下「提交」按鈕。提交後,應用程序將形成SQL查詢並連接到數據庫fillup Datatable - 轉換爲html代碼並在頁面上打印表格。我想要做的就是當他們按下提交按鈕時,當表格準備好顯示在頁面上時,顯示一個圖像(用戶在後臺進行查詢和建立表格等等的指示符),隱藏圖像。到目前爲止,這就是我所做的。現在Backgroundworker和圖像

BackgroundWorker bw = new BackgroundWorker(); 

protected void Page_Load(object sender, EventArgs e) 
{   
    bw.WorkerReportsProgress = true; 
    bw.WorkerSupportsCancellation = true; 
    bw.DoWork += new DoWorkEventHandler(bw_DoWork); 
    bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged); 
    bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);  
} 

public void SQL_Query() {...database connection and fill up data table } 

protected void Submit_Button(object sender, EventArgs e) 
{ 
    //LoadingImage.Visible = true; //this does not work 

    if (bw.IsBusy != true) 
    { 
     bw.RunWorkerAsync(); 
    }      
} 

private void bw_DoWork(object sender, DoWorkEventArgs e) 
{ 
    BackgroundWorker worker = sender as BackgroundWorker; 

    SQL_Query(); 
} 

private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 
{ 
    if ((e.Cancelled == true)) 
    { 
     this.tbProgress.Text = "Canceled!"; 
    } 
    else if (!(e.Error == null)) 
    { 
     this.tbProgress.Text = ("Error: " + e.Error.Message); 
    } 
    else 
    { 
     //when the query is completed, customize the data and print it on page as label 

     LoadingImage.Visible = false; 

     if (SQLQuery_Table.Rows.Count >= 1) 
     { 
      CustomizedTable(SQLQuery_Table); 
     } 

     string str = Display_Table(); 
     label.Text = str 

    } 
} 

,隨着代碼的問題是,LoadingImage.Visible = true;不會使按下按鈕時的圖像顯示。據我讀到的關於backgroundworker的其他類似帖子,它說UI不能在同一個線程中工作。我不想做任何進度條,因此對Reportprogress沒有興趣。簡單地,使圖像出現在提交按鈕上並在bw_RunWorkerCompleted中消失。如何在用戶按下提交按鈕時顯示圖像?我想保持簡單,所以如果我可以避免爲Image創建另一個背景工作,那將會很棒。謝謝!

回答

0

您可以使用一個.gif加載圖像是這樣的...

<asp:UpdateProgress id="updateProgress" runat="server"> 
    <ProgressTemplate> 
     <div style="position: fixed; text-align: center; height: 100%; width: 100%; top:0; right: 0; left: 0; z-index: 9999999; background-color: #000000; opacity: 0.7;"> 
      <asp:Image ID="imgUpdateProgress" runat="server" ImageUrl="~/images/ajax-loader.gif" AlternateText="Loading ..." ToolTip="Loading ..." style="padding: 10px;position:fixed;top:45%;left:50%;" /> 
     </div> 
    </ProgressTemplate> 
</asp:UpdateProgress> 
1

BackgroundWorker是一個ASP應用程序幾乎無用。當您完成異步操作時,您將響應發送回客戶端。 一旦您將回復發送給客戶端,您將無法再對其作出響應。您無法根據所描述的莊園中的異步操作結果更改UI。

要做到這一點的唯一方法是從客戶端可以請求更新操作的新請求,從而允許服務器向客戶端發送新信息。

+0

其實,LoadingImage.Visible = false在bw_RunWorkerCompleted中工作,因爲我相信異步操作已完成。所以爲什麼不能在執行bw.RunWorkerAsync()之前進行LoadingImage.Visible = true。爲什麼它不起作用? – user2848183

+0

@ user2848183當異步操作完成時,更改響應爲時已晚。它已經發送。這裏沒有建立任何雙向溝通。客戶端發出請求,服務器發送響應。這不像沒有客戶端/服務器關係的桌面應用程序,您的代碼可能因任何原因隨時影響UI。 – Servy

+0

現在確定它是有道理的。我如何解決這個問題?我需要做2個後臺工作(一個用於圖像,另一個用於sql查詢)並同步它們?如果您有任何示例,我將不勝感激! – user2848183