Event Handling in custom control

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • raghulvarma
    New Member
    • Oct 2007
    • 90

    Event Handling in custom control

    I have created a custom control to get the values and sum them, Here I am able to get display the controls but I am not able to add the values in the text box which means that I am not able to catch the event handling function how is it to be done and
    my second question is when I press the sum button the values in the textbox gets erased should I need to set the viewstate property if so how should i do that?
    below shown is my code
    custom control.cs


    Code:
          [DefaultEvent("Click")]
          public class WebCustomControl1 : WebControl
          {
          TextBox value1 = new TextBox();
          TextBox value2 = new TextBox();
          Label output = new Label();
          Button sresult = new Button();
          private string showresult;
          protected override void CreateChildControls()
          {
          //base.CreateChildControls();
          value1.TextMode = TextBoxMode.SingleLine;
          Controls.Add(value1);
          Controls.Add(new LiteralControl("<br>"));
          value2.TextMode = TextBoxMode.SingleLine;
          Controls.Add(value2);
          Controls.Add(new LiteralControl("<br>"));
          sresult.Text = "Show Result";
          Controls.Add(sresult);
          Controls.Add(new LiteralControl("<br>"));
          Controls.Add(new LiteralControl("&nbsp&nbspResult:&nbsp<b>"));
          Controls.Add(output);
          Controls.Add(new LiteralControl("</b>"));
          sresult.Click += new EventHandler(btnsumclicked);
          }
          public event EventHandler Click;
          void btnsumclicked(object sender, EventArgs e)
          {
          int a = int.Parse(value1.Text) + int.Parse(value2.Text);
          showresult = a.ToString();
          }
     
          protected virtual void onClick(EventArgs e)
          {
          if (Click != null)
          {
          Click(this, e);
          }
          }
          }
    In code behind i did not give any thing how should I handle the event in code behind
  • furuknap
    New Member
    • Jul 2008
    • 2

    #2
    Hello,

    You need to make sure that CreateChildCont rols is called early enough in the control life cycle. As you are talking about viewstate I assume you are doing this on an ASP.net web page, so try overriding the onload method and add EnsureChildCont rols() there:

    protected override void OnLoad(EventArg s e)
    {
    EnsureChildCont rols();
    [...]

    If you create the controls too late in the page life cycle the event wireup has already happened and no event handler will fire.

    .b

    Comment

    Working...