![](/img/trans.png)
[英]How to return a value from one class to another in C# (ASP.NET 2.0)
[英]Access a Label from one class file to another class file c# and asp.net
我创建了一个数据库连接类文件,如下所示。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Data.SqlClient;
using Asset;
namespace Asset.Modules
{
public class Dbconn
{
public bool CreateDBConnection()
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["AssetDBConnection"].ConnectionString);
try
{
con.Open();
return true;
}
catch (SqlException ex)
{
errorLabel.Text = ex.Message;
errorLabel.Visible = true;
return false;
}
}
}
在我的Default.aspx页上定义了errorLabel,如下所示;
<asp:Label ID="errorLabel" runat="server"></asp:Label>
我得到的错误是:名称'errorLabel'在当前上下文中不存在。
如何获取Dbconn文件以访问位于default.aspx页上的标签?
谢谢你的帮助。
可能这可能需要...
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
....accessing the database conn shared instance
Label myLabel = this.FindControl("errorLabel") as Label;
myLabel.Text = "my text";
}
}
您可以将CurrentHandler强制转换回Page对象,并在CreateDBConnection()
使用FindControl。
Page page = HttpContext.Current.CurrentHandler as Page;
Label lbl = page.FindControl("errorLabel") as Label;
lbl.Text = "There was an error.";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.