Search All Articles Submit your Website or Blog to A New Internet Library
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();
}
Subscribe to:
Post Comments (Atom)
Also Read other Top Articles
- JSON Serialization in VS 2008
- Implementing Forms Authentication in Silverlight Application.
- Making GridView Rows or Individual Cells Clickable and Selectable.
- Enabling browser back button for GridView Paging and Sorting in Ajax 1.1 and 3.5 (using Visual Studio 2005/ Visual studio 2008)
- How to pass values from User Control to Page or calling Page methods from User Control.
- What is WCF?
- New features in C# 4.0
- C# to VB.NET and VB.NET to C# online free converter tools.


0 comments:
Post a Comment
Post your comments/questions/feedback for this Article.