2011-11-24 67 views
1

我正在使用C#在後臺使用asp.net網站。我希望能夠更新頁面上的asp:標籤,可以說Page1.aspx。我希望根據其他文件夾中類(.cs)中某個函數的結果進行更新。這可能是behind.cs更新另一頁上的asp:標籤?

behind.cs

*some other code is here* 
bool correct = false; 
try 
{ 
    if (_myConn.State == ConnectionState.Closed) 
    { 
     _myConn.Open(); 
     myCommand.ExecuteNonQuery(); 
    } 
    if (Convert.ToInt32(myCommand.Parameters["@SQLVAR"].Value) < 1) 
    { 
     "Invalid Login" // I want to be the text of lblMessage.Text 
    } 
    else 
    { 
     correct = true;     
    } 
    _myConn.Close(); 
} 
catch (Exception ex) 
{ 
    "Error connecting to the database" // I want to be the text of lblMessage.Text 
} 
return correct; 

page1.aspx這個

<asp:label runat="server" ID="lblMessage" cssClass="error"></asp:label> 

如何更新在asp:從** behind.cs上page1.aspx這個*標籤? ?

回答

2

您不能直接從另一個班級訪問標籤。 您可以編寫一個TryLogin函數,該函數具有包含錯誤消息的out參數。

在Page1.cs

protected void BtnLogin_Clicked(object s, EventArgs e) 
{ 
    string errMess; 
    if(!Behind.TryLogin(out errMess) 
     lblMessage.Text = errMess; 
} 

在behind.cs

public static bool TryLogin(out string errMess) 
{ 
    *some other code is here* 
    errMess = null; 
    bool correct = false; 
    try 
    { 
    if (_myConn.State == ConnectionState.Closed) 
    { 
     _myConn.Open(); 
     myCommand.ExecuteNonQuery(); 
    } 
    if (Convert.ToInt32(myCommand.Parameters["@SQLVAR"].Value) < 1) 
    { 
     errMess = "Invalid Login" // I want to be the text of lblMessage.Text 
    } 
    else 
    { 
     correct = true;     
    } 
    _myConn.Close(); 
    } 
    catch (Exception ex) 
    { 
    errMess = "Error connecting to the database" // I want to be the text of lblMessage.Text 
    } 
    return correct; 
} 
+0

完美解釋。非常感謝。 =] – HGomez90

1

沒有簡單的方法讓您通過behind.cs中的代碼訪問page1.lblMessage成員。有兩種方法來處理它:

  • 對於正常的數據,從behind.cs代碼,在page1調用函數分配給lblMessage返回string
  • 對於例外事件(例如在您的示例中的無效登錄)在您的代碼中拋出異常。在調用behind.cs方法的代碼中,捕獲異常並將文本分配給lblMessage

在你的代碼應該添加在你的catch塊如下:

throw new MyException("Error connection to the database", e); 

您必須首先創建一個MyException類。然後在調用代碼中,catch(MyException)並顯示文字。如果您想在頁面代碼的一個位置處理所有異常,您還可以處理Page.Error事件。 MyException構造函數的e參數意味着提供基礎異常作爲InnerException。調試時始終保持原始的,技術上的信息異常。