[英]Update asp:label on another page?
我正在使用后台使用C#的asp.net网站。 我希望能够在页面上更新asp:标签,让我们说Page1.aspx 。 我希望根据其他文件夹中类(.cs)中函数的结果进行更新。 这可能是后面的.s 。
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>
如何从** behind.cs更新page1.aspx *上的asp:label?
您不能直接从另一个类访问标签。 您可以编写一个带有错误消息的out参数的TryLogin
函数。
在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;
}
有你访问没有简单的方法page1.lblMessage
从代码成员behind.cs
。 有两种方法可以处理它:
behind.cs
中的代码返回一个string
, page1
中的调用函数分配给lblMessage
。 behind.cs
方法的代码中,捕获异常并将文本分配给lblMessage
。 在代码中,应在catch块中添加以下内容:
throw new MyException("Error connection to the database", e);
您必须首先创建一个MyException
类。 然后在调用代码中, catch(MyException)
并显示文本。 如果要在页面代码的一个位置处理所有异常,也可以处理Page.Error
事件。 MyException
构造函数的e
参数意味着将底层异常作为InnerException
。 在调试时,保持原始的技术信息异常始终是有用的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.