chaitanyakrishna chaitanyakrishna - 3 months ago 24
ASP.NET (C#) Question

Renaming dynamically created controls

In my project, I was dynamically creating panels as per the user input. Each panel has a "Remove button". As the button is clicked the panel should be removed. But in order to hide it/ or delete the panel I need the button-id which is getting named automatically and I was not able to rename it.

input type="submit" name="ctl00$MainContent$ctl04" value="Copy PDF and Post Script files!"
usesubmitbehavior="false" EnableViewState="true" type="Button" id="645" name="645" />



addButtonCopyFiles[i].Attributes["id"] = templateId[i].Text;
addButtonCopyFiles[i].Attributes["name"] = templateId[i].Text;


This is how I named them, but the name doesn't get replaced. I even removed the "runat", "server" attribute.

Any help will be appreciated

Answer

The ID property of a Control can be explicitly set before it is added to the page.

Replace this code:

addButtonCopyFiles[i].Attributes["id"] = templateId[i].Text; 
addButtonCopyFiles[i].Attributes["name"] = templateId[i].Text; 
eachPanel[i].Controls.Add(addButtonCopyFiles[i]);

With this code:

addButtonCopyFiles[i].ID = templateId[i].Text;
eachPanel[i].Controls.Add(addButtonCopyFiles[i]);