且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在页面上找到我的用户控件。

更新时间:2023-12-03 08:40:46

我不确定你是如何放置控件的,但你可能需要通过使用Parent属性找到控件,如下所示

 CustomMessageControls uc1 =(CustomMessageControls) this  .Parent.FindControl(   MessageControl1); 





 CustomMessageControls uc1 =(CustomMessageControls) this  .Parent.Parent.FindControl(  MessageControl1\" 跨度>); 


I have make a common usercontrol (messagecontrol.ascx) which display message box. and I have place this usercontrol in my masterpage.

In my master page also a usercontrol named header.ascx which also call this usercontrol when user click on button of a header.ascx control. its working properly.

But when make a new cart.aspx page with same masterpage. and place a button and call button click same event which i write in header.ascx button its give null referece error.

code in Messagecontrol.ascx

public void Page_Load(object sender, EventArgs e)
{
lblMessage.Text = Message;
lblMessage1.Text = Message1;
if (Message != string.Empty && Message !=null)
SendErrorModelPopupExtender.Show();
}
public string Message { get; set; }
public string Message1 { get; set; }



code in Header.ascx (Here working Properly)

protected void btnCheckOut_Click(object sender, EventArgs e)
{
if (ShoppingCart.Instance.Items.Count == 0)
{
CustomMessageControls uc1 = (CustomMessageControls)this.Parent.Parent.FindControl("MessageControl1");
uc1.Message = "No Item Found in cart. Please add item in cart to checkout";
uc1.Message1 = "No Item Found";
uc1.Page_Load(uc1, EventArgs.Empty);
}
else
Response.Redirect("checkout.aspx");
}


Same code i call in cart.aspx page but its give error

code in cart.aspx

protected void btnCheckOut_Click(object sender, EventArgs e)
{
if (ShoppingCart.Instance.Items.Count == 0)
{
CustomMessageControls uc1 = (CustomMessageControls)this.FindControl("MessageControl1");
uc1.Message = "No Item Found in cart. Please add item in cart to checkout";
uc1.Message1 = "No Item Found";
uc1.Page_Load(uc1, EventArgs.Empty);
}
else
Response.Redirect("checkout.aspx");
}



When I click on cart.aspx page button it's error

I have also add the <%@ Reference VirtualPath="~/Controls/CustomMessageControls.ascx" %>

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 39: {
Line 40: CustomMessageControls uc1 = (CustomMessageControls)this.FindControl("MessageControl1");
Line 41: uc1.Message = "No Item Found in cart. Please add item in cart to checkout";
Line 42: uc1.Message1 = "No Item Found";
Line 43: uc1.Page_Load(uc1, EventArgs.Empty);


Please help me

Thanks
Ram Kumar

I'm not sure how you placed your controls, but you may need to find controls by using Parent property as below
CustomMessageControls uc1 = (CustomMessageControls)this.Parent.FindControl("MessageControl1");


or

CustomMessageControls uc1 = (CustomMessageControls)this.Parent.Parent.FindControl("MessageControl1");