interviews.dotnetthread.com

↑ 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


<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<div id="myDiv">
</div>
<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" />
</div>


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.setAttribute("id",divIdName);
    newdiv.innerHTML = "<input type='text'  name='TextBox"+num+"' value='TextBox"+num+"' >";
    ni.appendChild(newdiv);
  }
</script>


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();
alForm.Add(strValue);
strValue = "";
}
//Bind all textbox values to GridView.
GridView1.DataSource = alForm;
GridView1.DataBind();
}

Submit this story to DotNetKicks

No comments:

Post a Comment

Post your comments/questions/feedback for this Article.

 

Latest Articles