Search code examples
asp.netcode-behind

How can this codebehind be written better?


I have a form which has a single textbox that sends some data to the database upon hitting enter. Data is displayed below the textbox in a repeater control. Input data is displayed on the form immediately by binding the data to the repeater in the TextChanged event of that textbox.

In the CodeBehind, I am calling BindRepeater method twice, once on every new page load and once on the TextChanged event of the textbox.

How can this be rewritten to call the BindRepeater only once and still achieve the same effect?

protected void Page_Load(object sender, EventArgs e)
{    
    if (!this.IsPostBack)
    {
        BindRepeater();
    }
}

protected void BindRepeater()
{
    // data retrieval
    // repeater binding 
}

protected void CreateData(string newdata)
{
    // data insert
}

protected void TextBox1_TextChanged(object sender, EventArgs e)
{
    if (TextBox1.Text != string.Empty)
    {
        string _newData = TextBox1.Text.Trim();
        CreateData(_newData);
        BindRepeater();
    }
}

Solution

  • Use an event that would be fired after the text changed event to do the binding in. you can now remove it from the page load event.