Reputation: 867
I am trying to create a web page that starts off blank. With every button press new textboxes are added with a delete button to remove whatever row they want. That works great. The problem is I cannot access the dynamically created controls using C#.
In the code below I have them set up as <input
I've also tried using <asp:Textbox
but it also did not work. Request.Form["txtItemName1"]
always returns a blank string and I cannot do txtItemName1.Text
in the CS file because the textboxes don't exist yet.
How am I suppose to access the textboxes from the C# side?
Is there a better way to create controls dynamically?
<!-- jQuery -->
<script type="text/javascript">
$(window).load(function () {
$(document).ready(function () {
var counter = 1;
$(document).on('click', '.removeButtonByID', function () {
var _name = this.name.replace("btnRemove", "");
if (confirm('Are you sure you want to remove line ' + _name + '? This cannot be undone.')) {
$("#TextBoxDiv" + _name).remove();
}
});
$("#addButton").click(function () {
$('<div />', { 'id': 'TextBoxDiv' + counter }).html(
$('<label />').html('')
)
.append($('<div class="col-sm-1" style="width: 200px; padding-left: 7px; padding-right: 0px;"><input type="text" class="form-control" placeholder="Item Name" runat="server">').attr({ 'id': 'txtItemName' + counter, 'name': 'txtItemName' + counter }))
.append($('<div class="col-sm-1" style="width: 100px; padding-left: 7px; padding-right: 0px;"><input type="text" class="form-control" placeholder="D/I" runat="server">').attr({ 'id': 'txtDI' + counter, 'name': 'txtDI' + counter }))
.append($('<div class="col-sm-1"><label class="checkbox-inline"><input type="checkbox" value="">Subtotal</label>').attr({ 'id': 'subtotal' + counter, 'name': 'chkSubTotal' + counter }))
.append($('<br />'))
.append($('<button type="button"><span class="glyphicon glyphicon-minus"></span></button>').attr({ 'name': 'btnRemove' + counter, 'class': 'btn btn-danger removeButtonByID' }))
.appendTo('#TextBoxesGroup')
counter++;
});
});
});
</script>
<!-- HTML -->
<div id='TextBoxesGroup'>
<!-- Dynamically added textboxes here -->
</div>
<hr />
<button type="button" class="btn btn-default" id='addButton'>
<span class="glyphicon glyphicon-plus"></span>
</button>
Upvotes: 0
Views: 1750
Reputation: 2158
C# backend will not have access to dynamically jquery-created input fields. You can create server controls in ASP.Net with the code behind and using an UpdatePanel as in the example.
Upvotes: 1