2011-11-24 52 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。调试时始终保持原始的,技术上的信息异常。

相关问题