1

Hi I have created no. of textboxes(that no entered by user in txtcount textbox) dynamically. But i want to store those values into database. For that i used code in save button click event as follows :

protected void btnsave_Click(object sender, EventArgs e)
    {
        // Check how many textboxes the user created
        int count = Convert.ToInt32(txtcount.Text); 
        // Loop through them    
        for (int i=0; i < count; i++)
        {         
            // Get the TextBox      
            TextBox textbox = (TextBox)Page.FindControl("TextBox_" + i); 
            // Get the value      
            string val = textbox.Text;

            Response.Write(val);

         } 
    } 

But its giving error :

Object reference not set to an instance of an object.

What should i do? Please help me? Thank you.

2
  • What line does the stack trace say is the cause of the error? Have you tried to single-step through this code? Commented May 30, 2011 at 8:28
  • It gives error at line : string val = textbox.Text; Commented May 30, 2011 at 8:33

2 Answers 2

1

You should recreate your textboxes at every postback in the same order. The best place is page_init. Maybe you have reasons to do it at page_load. So you can get its values from viewstate.

Sign up to request clarification or add additional context in comments.

Comments

1

You need to re-create your dynamic controls on (every) post-back if you want to refer them. Use Page_Init or Page_Load event.

Yet another alternative (if there cannot be repeated post-backs) can be to read values from the request directly. For example,

string val = Request.Form["TextBox_" + i]

Of course, the request variable name may changed if you use templated controls (or master controls) in parent hierarchy. One of the solution in such case could be to store the sample control name (UniqueID) to be stored in view-state.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.