Accessing label from child control

2019-09-14 22:00发布

问题:

I have a control Orders.ascx in this control I have a reference to another control Grid.ascx something like this:

In my Orders.ascx I have :

   <asp:Label id="warnings" runat="server" />
   <uc:Grids id="uxGrid" runat="server/>

Now in the grid ( Grids.ascx ) I have a drop down control that has the quantities with a event handler method for on index change, when a different quantity is chosen in a row, it posts back and updates the price depending on the quantity. I need for each time it posts back to add a message to the label warnings in Orders.ascx, but my problem is that this label is in the parent control. I tried using FindControl and it DOES find it and I can set the text but it never updates the warnings label.

How can I update that label text from the drop down's on index change control?. It seems that it doesnt inject everytime i select the quantity.

回答1:

The simplest, cleanest way would be to use an event.

  1. Create an event argument class, derived from EventArgs, that includes a property for the data you want to pass:

     public class PriceChangeEventArgs: EventArgs
     {
         public decimal Price { get; set; }
     }
    
  2. Set up an event in the UserControl:

     public event EventHandler<PriceChangeEventArgs> PriceChanged;
    
  3. Raise the event when capturing the change in the drop down list index:

     protected void DropDownList1_SelectedIndexChanged(object source, EventArg e)
     {
         PriceChangeEventArgs args = new PriceChangeEventArgs();
         args.Price = Convert.ToDecimal(DropDownList1.SelectedValue);
         PriceChanged(this, args);
     }
    
  4. Handle the event in the parent control page or control:

    UserControl1.PriceChanged += new EventHandler<MyEventArgs>(page_PriceChanged);
    
    protected void page_PriceChanged(object source, MyEventArgs e)
    {
        Label1.Text = e.Price.ToString("C");
    }
    

This way, you haven't tied your user control in to your page: you can still use the user control other places, and the page doesn't need to know how the user control works, other than that it raises an event.

ETA: Added an important step I omitted: actually raising the event!