Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add a textchanged event to a textbox in the code-behind

i created a text-box through the code behind but was unable to add a text-changed event to it here is what i

 protected void insert(object sender, EventArgs e) 
{

}

protected void update(object sender, DayRenderEventArgs e) 
{
    TextBox tb = new TextBox();
    tb.TextChanged += "insert";

    e.Cell.Controls.Add(tb);

}

i tried this but it didn't work for me. what is the problem, thanks

like image 530
Wahtever Avatar asked Oct 25 '25 18:10

Wahtever


1 Answers

When you want to bind a handler to an event in code-behind, what you actually do is to write the name of the handler itself, not a string

    protected void Page_Load(object sender, EventArgs e)
    {
        TextBox textBox = new TextBox();
        textBox.TextChanged += new EventHandler(textBox_TextChanged);
    }

    protected void textBox_TextChanged(object sender, EventArgs e)
    {
        // Your code here
    }

To make a little more clear, imagine that C# has a list called EventHandler, and every time the text changes on the text box (blur event in client side), C# executes all the methods inside that list. Now, how do you add a method to that list? You use += operator. Now, if you want to add two handlers, you can write:

    protected void Page_Load(object sender, EventArgs e)
    {
        TextBox textBox = new TextBox();
        textBox.TextChanged += new EventHandler(textBox_TextChanged);
        textBox.TextChanged += new EventHandler(textBox_TextChanged2);
    }

    protected void textBox_TextChanged(object sender, EventArgs e)
    {
        // This method is the first in the list. So gets executed first.
    }

    protected void textBox_TextChanged2(object sender, EventArgs e)
    {
        // This method is the second in the list.
    }
like image 101
Saeed Neamati Avatar answered Oct 28 '25 06:10

Saeed Neamati



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!