views:

503

answers:

4

hi,

i have been trying to create controls dynamically on my web page using the StringBuilder class..and i dont quite seem to get through... any help would be appreciated.

i am trying to do this...

StringBuilder sbTest = new StringBuilder(string.Empty);

sbTest.Append("<input type=\"text\" id=\"txt1\" runat=\"server\" />");

Response.Write(sbTest.ToString());

The page for sure displays a TextBox on the browser which is easily accessible through JavaScript...but what i want is the control to be available on the Server Side too...so that when the page is posted back to the server i can easliy obtain the value that has been entered by the user into the textbox.

Can any 1 please help me with this....

thank you so much....

A: 

You can get the value from

Request["txt1"]
ck
+1  A: 

Provide a name-attribute and access it with:

Request.Form["txt1"]
Torbjörn Hansson
+2  A: 

Like Torbjörn Hansson says, if you just add a name attribute (and maybe remove runat="server" from your original snippet) you'll be able to access the submitted value but you'll only have a client-side HTML <input /> element.

If you are wanting to dynamically create server-side controls then you'll have to do something like this:

TextBox textbox = new TextBox {
    /* take care to create unique ID's if you're adding more than 1 TextBox */
    ID = "foo", 
    Text = "bar"
};

Controls.Add(textbox);
Ian Oxley
+2  A: 

In an answer almost about the something I answered this

You should do the things properly and not trying to reinvent the wheel.

Creating controls Dynamically you can choose 2 ways, the .NET way, or the Javascript way

Both are seen by any of the other, in other words, creating controls using the .NET way, javascript can see and use it and vice versa.

.NET way

in your HTML file add something like

<body>
   <form id="form" runat="server">
      <asp:PlaceHolder id="ph" runat="server" />
   </form>
</body>

in your script part

TextBox txt = new TextBox();
txt.ID = "myTxt";

ph.Controls.Add(txt);

you can easily get that TextBox in javascript using:

var myTxtValue = $("#myText").value();

Javascript Way

var txt = $("<input />", {
             id : "myTxt"
          });

txt.AppendTo("body");

in .NET you get the value using

string value = Request["myTxt"];

NOTE All javascript lines uses jQuery for simplify results

balexandre