i am working with dynamic TextBoxes and then Getting their Values in code behind file. I am creating these boxes using Javascript. my asp.net page code is
<script type="text/javascript">
$(document).ready(function () {
var counter = 1;
$("#addButton").click(function () {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.html('<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
return false;
});
});
</script>
</head>
<body>
<form id="form2" runat="server">
<h1>jQuery add / remove textbox example</h1>
<asp:TextBox runat="server" ID="txt1" type='text' name="textname" />
<asp:Panel runat="server" ID='TextBoxesGroup'>
</asp:Panel>
<asp:LinkButton ID="addButton" runat="server">Add TextBox</asp:LinkButton>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</body>
i have one Textbox shown on the page, which should shows only one values when no dynamic Textbox is created. My C# code is
protected void Button1_Click(object sender, EventArgs e)
{
string name = txt1.Text + ",";
if (TextBoxesGroup.Controls.Count > 0)
{
for (int i = 1; i <= TextBoxesGroup.Controls.Count; i++)
{
name += Request.Form["textbox" + i] + ",";
}
}
Label1.Text = name;
}
on asp:button click it should display all the values separated by (,). but it is only showing top 2 values, one of which is asp:Textbox and second is dynamic Textbox,, i want the values of all the Textboxes created dynamically, and when no dynamic textbox is added it should only show the value from asp:textBox... Thanks in Advance
Html input elements created through javascript on the client, are not going to be in TextBoxesGroup.Controls on the server.
Changes in the client DOM structure have no effect on the Page's Control tree. The only thing affected will be the content of HttpRequest during postback. One way to know how many dynamically created input elements contributed to Request.Form data is to pass this information as part of the request. This is why you will have to go with the hidden field suggestion. The hidden field value will bring back the count of client-side inputs. You have to set it in javascript every time you create a new input, read it in server-side code, convert to integer and use in your for loop.
Add
<asp:HiddenField runat="server" ID="txtDynamicCount" value="0" />
to the the markup inside form tag.
In javascript click event after counter++; line add
$("#txtDynamicCount").val(counter);
In Button1_Click:
int count;
if (!int.TryParse(txtDynamicCount.Value, out count))
count = 0;
for (int i = 1; i <= count; i++)
{
...
}
The important difference from the other answer is that textboxes (input elements) will not persist between form submits.
You cannot populate server controls in client side. Instead, you want to populate them from server. Here is the sample -
<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
<asp:LinkButton ID="addButton" runat="server" OnClick="btnAdd_Click">Add TextBox</asp:LinkButton>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><br/>
Posted Results: <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
private List<int> _controlIds;
private List<int> ControlIds
{
get
{
if (_controlIds == null)
{
if (ViewState["ControlIds"] != null)
_controlIds = (List<int>)ViewState["ControlIds"];
else
_controlIds = new List<int>();
}
return _controlIds;
}
set { ViewState["ControlIds"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
foreach (int id in ControlIds)
{
var textbox = new TextBox();
textbox.ID = id.ToString();
PlaceHolder1.Controls.Add(textbox);
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
var reqs = ControlIds;
int id = ControlIds.Count + 1;
reqs.Add(id);
ControlIds = reqs;
var textbox = new TextBox();
textbox.ID = id.ToString();
PlaceHolder1.Controls.Add(textbox);
}
protected void Button1_Click(object sender, EventArgs e)
{
var ids = ControlIds;
foreach (var id in ids)
{
var textbox = (TextBox)PlaceHolder1.FindControl(id.ToString());
Label1.Text += textbox.Text + ", ";
}
}
Related
Yes I tried using this operator technique, but On selecting 2 items from list box its giving me the sum of 3 or more items, Please let me know if the picture is visible to you..
Label1.Text = "";
foreach (int i in ListBox2.GetSelectedIndices()) {
Label1.Text += ListBox2.Items[i].Text + ",";
TextBox2.Text += ListBox2.Items[i] + "+";
}
Ok, I don't have your data, but lets just do this with say "id", and the Hotelname.
So, say this markup
<div style="float:left">
<asp:Listbox ID="LBHotels" runat="server"
Width="200px"
AutoPostBack="True"
OnSelectedIndexChanged="LBHotels_SelectedIndexChanged"
DataValueField="ID"
DataTextField="HotelName" Height="182px" SelectionMode="Multiple" >
</asp:Listbox>
</div>
<div style="float: left;margin-left:20px">
<h3>Occurance</h3>
<asp:TextBox ID="txtOccr" runat="server" Width="220px"></asp:TextBox>
</div>
<div style="float:left;margin-left:20px">
<h3>Results</h3>
<div style="text-align:right">
Total: <asp:TextBox ID="txtTotal" runat="server" TextMode="Number"></asp:TextBox><br />
Avg: <asp:TextBox ID="txtAvg" runat="server" TextMode="Number"></asp:TextBox>
</div>
</div>
(used div's, just float them left against each other - a nice easy way to place things around on a web form).
Ok, then this code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string strSQL =
"SELECT ID, HotelName FROM tblHotelsA ORDER BY HotelName";
SqlCommand cmdSQL = new SqlCommand(strSQL);
LBHotels.DataSource = MyRstP(cmdSQL);
LBHotels.DataBind();
}
}
And I did set auto-postback for the list box.
So, this code:
protected void LBHotels_SelectedIndexChanged(object sender, EventArgs e)
{
string sValues = ""; // string list of values for display into text box
int intTotal = 0; // total value
int[] Choices = LBHotels.GetSelectedIndices();
for (int i = 0; i < Choices.Length;i++)
{
ListItem MyChoice = LBHotels.Items[Choices[i]];
if (sValues != "")
sValues += "+";
sValues += MyChoice.Value;
intTotal += Convert.ToInt32(MyChoice.Value);
}
txtOccr.Text = sValues;
txtTotal.Text = intTotal.ToString();
txtAvg.Text = "0";
if (intTotal > 0)
txtAvg.Text =
String.Format("{0:0.####}", (decimal)intTotal / Choices.Length);
}
And the result is now this:
:
I'm new to coding, hope some can help me a bit, I got stuck at retrieving data from my Dynamically added Text boxes in ASP.NET.
I Master Site and a Content site. I have added some buttons to the content site there are adding or removing the textboxes, after what's needed by the user.
My problem is, that i'm not sure how to retrieve the data correct. hope some body can help me on the way.
My Content site:
<%# Page Title="" Language="C#" MasterPageFile="~/main.master" AutoEventWireup="true" CodeFile="CreateRMA.aspx.cs" Inherits="CreateRMA" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="mainsite" Runat="Server">
<div id="div_fortext" class="div_fortext">
<p class="header2">
Opret RMA Sag
</p>
<p class="text1">
Her Kan de oprette alt det udstyr der skal sendes til reperation hos zenitel.
</p>
</div>
<div id="div_insert_devices" runat="server">
</div>
// 3 buttons one who add, one who remove textboxes and a submit button
<asp:Button ID="btnAddRow" runat="server" Text="Add Row" CssClass="butten1" OnClick="btnAddRow_Click" />
<asp:Button ID="btnRemoveRow" runat="server" Text="Remove Row" CssClass="butten1" OnClick="btnRemoveRow_Click" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" CssClass="butten1" OnClick="btnSubmit_Click" />
</asp:Content>
My C# code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class CreateRMA : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ViewState["DeviceCount"] = ViewState["DeviceCount"] == null ? 1 : ViewState["DeviceCount"];
InsertLine();
}
}
private void InsertLine()
{
int DeviceCount = int.Parse(ViewState["DeviceCount"].ToString());
for (int i = 0; i < DeviceCount; i++)
{
LiteralControl text = new LiteralControl("<div class=\"divPerDevice\">");
div_insert_devices.Controls.Add(text);
TextBox txtbox = new TextBox();
txtbox.ID = "serial" + i;
txtbox.CssClass = "textbox1";
txtbox.Attributes.Add("runat", "Server");
div_insert_devices.Controls.Add(txtbox);
text = new LiteralControl("</div>");
div_insert_devices.Controls.Add(text);
}
}
protected void btnAddRow_Click(object sender, EventArgs e)
{
int count = int.Parse(ViewState["DeviceCount"].ToString());
count++;
ViewState["DeviceCount"] = count;
InsertLine();
}
protected void btnRemoveRow_Click(object sender, EventArgs e)
{
int count = int.Parse(ViewState["DeviceCount"].ToString());
count--;
ViewState["DeviceCount"] = count;
InsertLine();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
// Submit - save the textboxes to Strings ??? Can any body help
}
}
((TextBox)div_insert_devices.FindControl("txtboxname")).Text
Try this one
you can use the following code
protected void btnSubmit_Click(object sender, EventArgs e)
{
// Submit - save the textboxes to Strings ??? Can any body help
int DeviceCount = int.Parse(ViewState["DeviceCount"].ToString());
for (int i = 0; i < DeviceCount; i++)
{
TextBox txtbx= (TextBox)div_insert_devices.FindControl("serial" + i);
if(txtbx!=null)
{
var value= txtbx.Text;
}
}
}
The way i would attempt this is like the following:
protected void btnSubmit_Click(object sender, EventArgs e)
{
foreach (Control control in div_insert_devices.Controls){
if (control.GetType() == typeof(textbox)){
Textbox myDynTextbox = (Textbox)control;
Var myString = myDynTextbox.Text;
Please note this code can be simplyfied further but, i have written it this was so you understand how it would work, and my advise would be to store all the strings in a collection of Strings, making it easier to maintain.
}
}
}
Kush
Why don't you use javascript to save the value of textbox. just hold the value in some hidden field and bind it everytime when you need it.
Hi I found the solution after some time here... I did not got any of examples to work that you have provided. sorry.
But I almost started from scratch and got this to work precis as I wanted :)
My Content Site:
<%# Page Title="" Language="C#" MasterPageFile="~/main.master" AutoEventWireup="true" CodeFile="CreateRMA.aspx.cs" Inherits="CreateRMA" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="mainsite" Runat="Server">
<div id="div_fortext" class="div_fortext">
<p class="header2">
Opret RMA Sag
</p>
<p class="text1">
Some TEXT
</p>
</div>
</div>
<asp:Button ID="btnAddRow" runat="server" Text="Add Row" CssClass="butten1" OnClick="btnAddRow_Click" />
<asp:Button ID="btnRemoveRow" runat="server" Text="Remove Row" CssClass="butten1" OnClick="btnRemoveRow_Click" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" CssClass="butten1" OnClick="btnSubmit_Click" />--%>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:PlaceHolder runat="server" id="DynamicDevices"></asp:PlaceHolder>
<asp:Button id="btnAddTextBox" runat="server" text="Tilføj" CssClass="butten1" OnClick="btnAddTextBox_Click" />
<asp:Button id="btnRemoveTextBox" runat="server" text="Fjern" CssClass="butten1" OnClick="btnRemoveTextBox_Click" />
<asp:Button runat="server" id="Submit" text="Submit" CssClass="butten1" OnClick="Submit_Click" />
<br /><asp:Label runat="server" id="MyLabel"></asp:Label>
</asp:Content>
My C# code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class CreateRMA : System.Web.UI.Page
{
static int myCount = 1;
private TextBox[] dynamicTextBoxes;
private TextBox[] Serial_arr;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
myCount = 1;
}
}
protected void Page_Init(object sender, EventArgs e)
{
Control myControl = GetPostBackControl(this.Page);
if (myControl != null)
{
if (myControl.ID.ToString() == "btnAddTextBox")
{
myCount = myCount >= 30 ? 30 : myCount + 1;
}
if (myControl.ID.ToString() == "btnRemoveTextBox")
{
myCount = myCount <= 1 ? 1 : myCount - 1;
}
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
dynamicTextBoxes = new TextBox[myCount];
Serial_arr = new TextBox[myCount];
int i;
for (i = 0; i < myCount; i += 1)
{
LiteralControl literalBreak = new LiteralControl("<div>");
DynamicDevices.Controls.Add(literalBreak);
TextBox Serial = new TextBox();
Serial.ID = "txtSerial" + i.ToString();
Serial.CssClass = "";
DynamicDevices.Controls.Add(Serial);
Serial_arr[i] = Serial;
TextBox textBox = new TextBox();
textBox.ID = "myTextBox" + i.ToString();
DynamicDevices.Controls.Add(textBox);
dynamicTextBoxes[i] = textBox;
literalBreak = new LiteralControl("</div>");
DynamicDevices.Controls.Add(literalBreak);
}
}
public static Control GetPostBackControl(Page thePage)
{
Control mycontrol = null;
string ctrlname = thePage.Request.Params.Get("_EVENTTARGET");
if (((ctrlname != null) & (ctrlname != string.Empty)))
{
mycontrol = thePage.FindControl(ctrlname);
}
else
{
foreach (string item in thePage.Request.Form)
{
Control c = thePage.FindControl(item);
if (((c) is System.Web.UI.WebControls.Button))
{
mycontrol = c;
}
}
}
return mycontrol;
}
protected void Submit_Click(object sender, EventArgs e)
{
int deviceCount = Serial_arr.Count();
DataSet ds = new DataSet();
ds.Tables.Add("Devices");
ds.Tables["Devices"].Columns.Add("Serial", System.Type.GetType("System.String"));
ds.Tables["Devices"].Columns.Add("text", System.Type.GetType("System.String"));
for (int x = 0; x < deviceCount; x++)
{
DataRow dr = ds.Tables["Devices"].NewRow();
dr["Serial"] = Serial_arr[x].Text.ToString();
dr["text"] = dynamicTextBoxes[x].Text.ToString();
ds.Tables["Devices"].Rows.Add(dr);
}
//MyLabel.Text = "der er " + deviceCount +" Devices<br />";
//foreach (TextBox tb in Serial_arr)
//{
// MyLabel.Text += tb.Text + " :: ";
//}
//MyLabel.Text += "<br />";
//foreach (TextBox tb in dynamicTextBoxes)
//{
// MyLabel.Text += tb.Text + " :: ";
//}
}
protected void btnAddTextBox_Click(object sender, EventArgs e)
{
}
protected void btnRemoveTextBox_Click(object sender, EventArgs e)
{
}
}
Thanks For all the help anyway :)
Hope somebody can use this.
Best regards Kasper :)
Im having a javascript code wherein im accessing div in aspx page using innerHTML attribute and want to do following: 1) Get entire content of that div tag.
2) Bind the entire contents of that div tag to a variable say res .
3) Give the value in res to a hidden control in aspx page and finally
4) Render that value from hidden field and use it in aspx.cs code behind.
My aspx page is as below
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script type ="text/javascript" language = "javascript">
function inject()
{
var res = document.getElementById('<%= div.ClientID %>').innerHTML.toString();
document.getElementById('hidden1').value = res;
}
</script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:Button ID="BtnAdd" runat="server" Text="Add" onclick="BtnAdd_Click" Width="67px" />
<div id = "div" runat ="server">
</div>
<input type = "hidden" id = "hidden1" value = "" />
<asp:Label ID = "lbl" Text = "Final answer goes here" runat = "server"/>
</asp:Content>
and the code behind to access it as as follows
public partial class _Default : System.Web.UI.Page
{
public string str = "* is the capital of *";
StringBuilder sb = new StringBuilder();
public static int count = 1;
public string res;
protected void Page_Load(object sender, EventArgs e)
{
StringBuilder htm = new StringBuilder();
for (int j = 0; j < str.Length; j++)
{
if (str[j] == '*')
{
string res = "<input type = 'text' id ='" + count + "' value = ''/>";
htm = htm.Append(res);
count++;
}
else
{
htm = htm.Append(str[j]);
}
}
div.InnerHtml = htm.ToString();
}
protected void BtnAdd_Click(object sender, EventArgs e)
{
this.Page.RegisterStartupScript("<Script>", "<Script type='text/javascript'> inject();</Script>");
string res = Request.Form["hidden1"];
lbl.Text = res;
}
}
Now code is executing but im not getting the entire content from the innerHTML thing onto res variable in the code behind. By entire content i mean everything within to tag. Im sure i have messed it somewhere or if its an wrong approach can i be suggested a better way??
Thanks for taking time onto this
I am a noob and i've been trying to figure out how we may assign an ID to asp:TextBox tags on creation in ASP.NET using c#.
Example:
I need to create a thread that may have multiple textboxes.
When a user clicks on a button, a text box must be generated with an ID say, txt01. On being clicked the second time, the ID of the generated text box must be txt02 and so on..depending on the number of clicks.
Thanks in Advance.
Remember last ID in some variable, for example int lastID, then in button's onClick method when creating the new TextBox assign its ID="txt"+lastID;.
You have to persist the lastID during page postbacks, you can store it in a ViewState.
Take and placeholder in your aspx page: eg: <asp:PlaceHolder runat="server" ID="pholder" />
and in code behind:
TextBox txtMyText = new TextBox();
tb1.ID = YourDynamicId;
pholder.Controls.Add(txtMyText);
You can save current id in ViewState and get the same id and assign incremented id to your dynamic textbox.
Try This:
int i = 1;
if (ViewState["i"] == null)
{
ViewState["i"] = i;
}
else
i = (int)ViewState["i"];
PlaceHolder1.Controls.Clear();
for (int j = 1; j <= i; j++)
{
TextBox TextBox = new TextBox();
TextBox.ID = "TextBox" + j.ToString();
PlaceHolder1.Controls.Add(TextBox);
}
ViewState["i"] = i + 1;
add this on your .aspx page
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
Hope This help.
I think this is what you are looking for -
You will notice that I have used Page_Init because if you create/add the controls in Page_Load then FindControl will return null in PostBack. And also any data you entered in the dynamically added controls will not persist during Postbacks.
But Page_Init is called before ViewState or PostBack data is loaded. Therefore, you can not use ViewState or any other controls to keep the control count. So I have used Session to keep the count.
Try it out and let me know what you think.
ASPX Page
<form id="form1" runat="server">
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:Button ID="btnCreate" runat="server" Text="Create" OnClick="btnCreate_Click" />
<asp:Button ID="btnRead" runat="server" Text="Read" OnClick="btnRead_Click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>
Code Behind
protected int NumberOfControls
{
get { return Convert.ToInt32(Session["noCon"]); }
set { Session["noCon"] = value.ToString(); }
}
private void Page_Init(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
//Initiate the counter of dynamically added controls
this.NumberOfControls = 0;
else
//Controls must be repeatedly be created on postback
this.createControls();
}
private void Page_Load(object sender, System.EventArgs e)
{
}
protected void btnCreate_Click(object sender, EventArgs e)
{
TextBox tbx = new TextBox();
tbx.ID = "txtData"+NumberOfControls;
NumberOfControls++;
PlaceHolder1.Controls.Add(tbx);
}
protected void btnRead_Click(object sender, EventArgs e)
{
int count = this.NumberOfControls;
for (int i = 0; i < count; i++)
{
TextBox tx = (TextBox)PlaceHolder1.FindControl("txtData" + i.ToString());
//Add the Controls to the container of your choice
Label1.Text += tx.Text + ",";
}
}
private void createControls()
{
int count = this.NumberOfControls;
for (int i = 0; i < count; i++)
{
TextBox tx = new TextBox();
tx.ID = "txtData" + i.ToString();
//Add the Controls to the container of your choice
PlaceHolder1.Controls.Add(tx);
}
}
store the id in a ViewState something like this
First initialise a count variable similiar to this.
in your class write this
protected int replyCount //declare the variable
{
get { return (int)ViewState["replyCount"]; }
set { ViewState["replyCount"] = value; }
}
In your page Load write this to initialise the replyCount if its not a postback;
protected void Page_Load(object sender, EventArgs e)
{
if(!page.IsPostBack)
{
replyCount = 0; //initialise the variable
}
}
then while creating dynamic textboxes
protected void Button_Click(Object sender, EventArgs e)
{
TextBox tb = new TextBox();
tb.id = "tb" + replycount; //use the variable
replycount++; // and after using increment it.
form.controls.add(tb); // assuming your form name is "form"
}
Thats it you should do.
I have created 3 dynamic texbox. At the run time i wanna enter some values in that textbox. if click the button then the entered textboxes value should be display in one dynamic label control.
please help me with some samples
USe Page.FindControl to access to dynamically created controls
You can do it client side, assuming your using jquery something like:
<span name="display" id="display"></span>
<input name="text1" id="text1" />
<input name="text2" id="text2" />
<input name="text3" id="text3" />
<input type="button" id="button1" />
<script>
$("#button1").click(function() {
$("#display").html($("#text1").val() + $("#text2").val() + $("#text3").val());
});
</script>
Try this code in asp.net
.CS file
protected override void OnPreInit(EventArgs e)
{
Label lbl = new Label();
lbl.ID = "mylbl";
lbl.ClientIDMode = System.Web.UI.ClientIDMode.Static;
form1.Controls.Add(lbl);
for (int i = 0; i < 3; i++)
{
TextBox txt = new TextBox();
txt.ID = "txt" + i;
form1.Controls.Add(txt);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Label lbl = form1.FindControl("mylbl") as Label;
lbl.Text = "";
for (int i = 0; i < 3; i++)
{
TextBox txt = form1.FindControl("txt" + i) as TextBox;
lbl.Text += txt.Text;
}
}
.aspx File
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>
</form>