I have a method called NewBatch_GetAndSetBatchID.
When I call this methode in the Page_Load methode it works perfectly.
But when I call this methode from a button (on the same page), I get:
Null reference exeption Object reference not set to an instance of an object.
It throws an error at:
BatchNoTextBox.Text = (batchID += 1).ToString();
When I debug, I can see that my batchID is filled with a value.
This is my code:
public void NewBatch_GetAndSetBatchID()
    {
        FormView1.ChangeMode(FormViewMode.Insert);
        string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
        try
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                SqlCommand sqlCommando = new SqlCommand("SELECT MAX(BatchNo) FROM BM_BrewBatchHeader", conn);
                try
                {
                    conn.Open();
                    batchID = Convert.ToInt32(sqlCommando.ExecuteScalar());
                }
                catch (Exception)
                {
                }
                finally
                {
                    conn.Close();
                }
            }
        }
        catch (SqlException error)
        {
        }
        try
        {
            TextBox BatchNoTextBox = (TextBox)FormView1.FindControl("BatchNoTextBox");
            BatchNoTextBox.Text = (batchID += 1).ToString();
        }
        catch (Exception)
        {
            throw;
        }
    }
What can be the problem here?
I found the solution on another forum: I have to use the PreRender trigger from the FormView. With the code below it works fine. When I now set the Formview to insert or edit mode the code executes perfectly.
protected void FormView1_PreRender(object sender, EventArgs e)
        {
            // if the mode is Edit or Insert
            if (this.FormView1.CurrentMode == FormViewMode.Edit || this.FormView1.CurrentMode == FormViewMode.Insert)
            {
                TextBox BatchNoTextBox = (TextBox)FormView1.FindControl("BatchNoTextBox");
                BatchNoTextBox.Text = (batchID += 1).ToString();
            }
        }
