↑ Grab this Headline Animator

Monday, December 1, 2008

Adding HTML controls dynamically through JavaScript and Accessing them in Code behind page(.cs)

Foradding HTML controls dynamically through JavaScript and Accessing them in backend code

<asp:GridView ID="GridView1" runat="server">
<div id="myDiv">
<input type="button" id="btnOfficial" value="Add Another TextBox" onclick="addHTMLControl();" />
<input type="hidden" value="1" id="theValue" runat="server" />
<asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" Text="Show All in Grid" />

On button click just call the below Javascript function where we are creating new HTML element and appending into DIV.

<script type="text/javascript">
function addHTMLControl() {
    var ni = document.getElementById("myDiv");
    var numi = document.getElementById("theValue");    
    var num = (document.getElementById("theValue").value -1)+2;
    numi.value = num;
    var newdiv = document.createElement("div");
    var divIdName = "my"+num+"Div";
    newdiv.innerHTML = "<input type='text'  name='TextBox"+num+"' value='TextBox"+num+"' >";

We form new HTML textbox control and append to DIV. Not here that we are using appendChild method for appending new element but not innerHTML.

In Code behind to access the dynamically generated HTML Controls do the following (Using Request.Form)

protected void btnSave_Click(object sender, EventArgs e)
ArrayList alForm = new ArrayList();
//As textbox id started with 2 like TextBox2,TextBox3…..
for (int i = 2; i < Request.Form.Count - 2; i++)
string strId = "TextBox" + i.ToString();
string strValue = Request.Form[strId].ToString();
strValue = "";
//Bind all textbox values to GridView.
GridView1.DataSource = alForm;

Submit this story to DotNetKicks

No comments:

Post a Comment

Post your comments/questions/feedback for this Article.


Latest Articles