6 c# asp.net null user-controls event-handling
我已经对此进行了广泛的搜索,但找不到我的问题的解决方案.我试图在该页面上的用户控件的页面后面的代码中调用一个函数.
我有一个使用母版页的Web应用程序.我正在添加一个我写入其中一个内容页面的用户控件.我通过从工具箱中拖放来将用户控件添加到aspx页面.我能够从后面的代码中看到用户控件,但我无法访问公共函数.为了解决这个问题,我在后面的代码中创建了一个用户控件的对象,并使用了LoadControl函数.所有这一切似乎都很好.
我遇到的问题是当我试图从aspx页面挂钩到用户控件的EventHandler时.一切都编译并运行得很好,但我没有看到页面上发生任何事情.我认为问题是EventHandler始终为null.
用户控制代码
public partial class ucBuyerList : System.Web.UI.UserControl
{
public delegate void BuyerSelectedEventHandler(object sender, EventArgs e);
public event BuyerSelectedEventHandler BuyerSelected;
private string name = "";
public string Name
{
get { return name; }
set { name = value; }
}
private string auid = "";
public string AUID
{
get { return auid; }
set { auid = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
}
private void OnBuyerSelected(EventArgs e)
{
if (BuyerSelected != null)
{
BuyerSelected(this, new EventArgs());
}
}
protected void lbBuyerList_SelectedIndexChanged(object sender, EventArgs e)
{
SetNameAndAUID();
OnBuyerSelected(e);
}
private void SetNameAndAUID()
{
name = lbBuyerList.SelectedItem.Text;
auid = lbBuyerList.SelectedItem.Value;
}
}
Run Code Online (Sandbox Code Playgroud)
父页面代码
public partial class frmBuyerInformation : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Master.changePageTitle("Buyer Information");
buyerList.BuyerSelected += new ucBuyerList.BuyerSelectedEventHandler(buyerListControl_BuyerSelected);
}
void buyerListControl_BuyerSelected(object sender, EventArgs e)
{
DisplayBuyerInformation();
}
public void DisplayBuyerInformation()
{
tbName.Text = buyerList.Name;
tbAUID.Text = buyerList.AUID;
}
}
Run Code Online (Sandbox Code Playgroud)
谁能看到我做错了什么?
编辑:此问题已得到解决.上面的代码snippits现在正在运行.如果有人遇到我遇到的问题,你可以对上面的代码进行建模.确保AutoEventWireup="true"在aspx和ascx页面中都有.感谢June Paik提供的解决方案.感谢Diego De Vita的输入.
小智 2
我也已经在事件中挣扎了很长一段时间。如今我总是以这种方式创建它们,因为这是我知道它有效的唯一方法。还没有用您的代码对其进行测试,但无论如何都是这样:
public partial class ucBuyerList : System.Web.UI.UserControl
{
public delegate void BuyerSelectedEventHandler(object sender, EventArgs e);
public event BuyerSelectedEventHandler BuyerSelected;
public string Name;
public string AUID;
protected void Page_Load(object sender, EventArgs e)
{
//Select the first buyer in the list when the user control loads
if (!IsPostBack)
{
lbBuyerList.SelectedIndex = 0;
}
}
private void OnBuyerSelected(EventArgs e)
{
BuyerSelectedEventHandler handler = BuyerSelected;
if (handler != null)
{
handler(this, new EventArgs());
}
}
protected void lbBuyerList_SelectedIndexChanged(object sender, EventArgs e)
{
Name = lbBuyerList.SelectedItem.Text;
AUID = lbBuyerList.SelectedItem.Value;
OnBuyerSelected(e);
}
}
Run Code Online (Sandbox Code Playgroud)
在父页面中,您可以按照您已经执行的方式调用您的函数。
| 归档时间: |
|
| 查看次数: |
11314 次 |
| 最近记录: |