Create Controls From Code Behind

I was Creating control that had fields created dynamically according to data passed

and according to the controls created some java scripts need to be added with them

and here are some tips I learned

the id you assign to the control in runtime some times is not the actual id of the control in the html client side code specially when this control created inside A Custom User Control..

So in order to get the actual client side control id to use it in JavaScript code use Control.ClientID to get it.

if you added an html control that runat server  in a Custom user control

this html control wont appear in the C# code behind code unless you add some thing like that.

protected global::System.Web.UI.HtmlControls.HtmlGenericControl MainDiv;

To render html code in a div that run at server use the following

MainDiv.InnerHtml = HtmlString;

 

you can create asp control and render it into html string using

StringWriter sw = new StringWriter();

control.RenderControl(new HtmlTextWriter(sw));

MainDiv.InnerHtml = sw.ToString();

 

How ever if the rendered asp control have some event handlers

those handlers wont be invoked for some strange reason I didn’t find out it yet.

 

but you can create controls with event handlers in other way by

using System.Web.UI.WebControls.Table;

usingSystem.Web.UI.WebControls.TableRow;

using System.Web.UI.WebControls.TableCell;

 

 

and finally after creating the control from code behind add it the controls of the cell …

TableCell.controls.add(control);

TableRow.cells.add(TableCell);

Table.Rows.add(TableRow);

 

some Times you need to add some tags like style and things like that to the control this can done using

Control.Attributes.add(StringKey,StringValue);

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
TAGS:  , ,


1 Comment

  1. Thanks for writing this.

 

View Abdel-Rahman Awad's profile on LinkedIn

Archives

 

Rss Feed Tweeter button Facebook button Linkedin button Delicious button Digg button