2

I am creating a table dynamically using c# and I am adding buttons to each cells. I need to assign button IDs for each of them so I can identify them later. I used following code for that.

bt.ID = rowIndex + c.ToString();   //bt.ID = "newID";

But when I try to access this button later it gives me an error.

Button seatButton = (Button)this.FindControl("a1");
seatButton.BackColor = Color.Red;   //Gives an error here
seatButton.Enabled = false;         //Gives an error here

I think the problem is with changing the button ID. I need to know the reason of this error and the cure..

2

1 Answer 1

3

Here your seatButton must be null from the statement:

Button seatButton = (Button)this.FindControl("a1");

Rather than just doing this.FindControl , you can look for the placeholder of your control first and then get the button control, or search recursively through all the page controls.

Method I: Using ContentPlaceHolder way.

ContentPlaceHolder contentPH = (ContentPlaceHolder)this.Master.FindControl("MyContentPlaceHolder");
 Button seatButton = (Button)contentPH.FindControl("a1");

Method II:: Search recursively through the page controls.

Call getControl method once from appropriate part of your code

GetControl(Page.Controls);

// and method looks like:

private void GetControl( ControlCollection controls )
{
  foreach (Control ctrl in controls)
{
     if(ctrl.ID == "a1")
    {
       seatButton = (Button)ctrl;
    }

     if( ctrl.Controls != null)
     // call recursively this method to search nested control for the button 
     GetControl(ctrl.Controls);    
}

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

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.