Question

I have a simple UserControl that I've created that simply allows a user to enter the date. For the time being, it has a single Textbox with ID="tbDate". I am trying to dynamically add this control multiple times via (for example) placeholder.Controls.Add(LoadControl()) but am receiving the error "An entry with the same key already exists". I could, perhaps, change the ID of the elements but then it would be difficult to grab the value entered by the user.
Does anyone have an idea on this?

Thanks!

Was it helpful?

Solution

I generate a unique identifier as part of a Component class that I created and then use that value as the Control.ID. You can generate this unique value in any way you'd like but I am storing it as part of a database table. In the end it isn't that important since when the class is instantiated the values are initialized and consistent throughout the run of the application.

The class has a private instance variable:

private Control _control;

When adding the control to the form (and, specifically, the placeholder) I do something similiar to this. Note that c references my created class.

c.Control.ID = c.ComponentName + c.UniqueIdentifier;
phHere.Controls.Add(c.Control);

Then when I need to reference the control at a later point I essentially reverse the steps above:

string component = c.ComponentName + c.UniqueIdentifier;
UserControl uc = (UserControl)ph.FindControl(component);

Hopefully this helps. If you have any questions please feel free to ask. The root of the problem, though, is that the Control.ID must be set in order to avoid the error.

Thanks

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top