c# - How To generate unique ID for controls inside a User Control -
i have user control in have 1 label.
<asp:label id="lblproductionname" runat="server" text="production name come here"> </asp:label> i render given uc code behind using function:
private string rendercontrol(control control) { stringbuilder sb = new stringbuilder(); stringwriter sw = new stringwriter(sb); htmltextwriter writer = new htmltextwriter(sw); control.rendercontrol(writer); return sb.tostring(); } after rendering, output string:
<span id="lblproductionname">production name come here</span> now, when put 2 instances of same user control, same span id in output string.
i want generate 2 different ids 2 instances of user control. how can generate it?
you might try this:
private dictionary<string, int> controlinstances = new dictionary<string, int>(); private string rendercontrol(control control) { stringbuilder sb = new stringbuilder(); stringwriter sw = new stringwriter(sb); htmltextwriter writer = new htmltextwriter(sw); int index = getoraddcontrolinstancecount(control); control.clientidmode = clientidmode.static; control.id = control.gettype().name + index; control.rendercontrol(writer); return sb.tostring(); } private int getoraddcontrolinstancecount(control control) { string key = control.gettype().name; if (!controlinstances.containskey(key)) { controlinstances.add(key, 0); } return controlinstances[key]++; } more advanced solution maybe use namingcontainer.
Comments
Post a Comment