I am dynamically creating a table with data and check boxes in it, my problem is when i check to see one specific check-box is checked, out of many, it resets to the default state of false (note: its not just one it doesn't work with, it works with non of the generated check boxes)
Before i create the page_load function i create the check box, further down i create the table, and populate it with data, then i set up a function to check on a click to see if the box was indeed checked, iv'e tried many iterations of this with no luck
protected void table_builder(SqlDataReader readerinfo)
{
//Create a new step for the user
step3label.Text = "3.";
//Table header
TableHeaderRow hr = new TableHeaderRow();
TableHeaderCell hc = new TableHeaderCell();
TableHeaderCell hc2 = new TableHeaderCell();
TableHeaderCell hc3 = new TableHeaderCell();
hr.Cells.Add(hc);
hc.Text = "ID"; //Assign header 1 with a name
hr.Cells.Add(hc2);
hc2.Text = "Name";//Assign header 2 with a name
hr.Cells.Add(hc3);
hc3.Text = "Selection";
Table1.Rows.Add(hr);
//Dynamic Table Generation
int numcells = 3;
int triswitch = 0;//this is use to chose which cell is made, id, name or selection
string checkboxID = null;
while (readerinfo.Read()) //execute the following aslong as there is data to fill the table with
{
for (int j = 0; j < 1; j++)
{
TableRow r = new TableRow();
for (int i = 0; i < numcells; i++)
{
TableCell c = new TableCell();
switch (triswitch)
{
case 0: // this case sets the info for the feild id
c.Text = readerinfo.GetSqlGuid(0).ToString();
checkboxID = readerinfo.GetSqlGuid(0).ToString();
r.Cells.Add(c);
triswitch = 1;
break;
case 1:
c.Text = readerinfo.GetString(1);
r.Cells.Add(c);
triswitch = 2;
break;
case 2:
Checkbox_creator(checkboxID,ref c);
r.Cells.Add(c);
triswitch = 0;
break;
}
}
Table1.Rows.Add(r);
}
}
}
protected void Checkbox_creator(string id,ref TableCell send)
{
//create the checbox
ckbx = new CheckBox();
ckbx.ID = "CBX" + checkboxid.ToString();
checkboxid++;
ckbx.InputAttributes.Add("value", id);
send.Controls.Add(ckbx); //add the chekbox to the cell
checkboxidlist.Add(id);//add the id of the checkbox to the list
}
//
//AFTER DATATABLE IS LOADED
//
public void test()
{
// Find control on page.
CheckBox myControl1 = (CheckBox)Table1.FindControl("CBX0");
if (myControl1 != null)
{
// Get control's parent.
Control myControl2 = myControl1.Parent.Parent.Parent;
Response.Write("Parent of the text box is : " + myControl2.ID);
if (myControl1.Checked == true)
{
Response.Write("check box checked");
}
}
else
{
Response.Write("Control not found");
}
}
//on Submit button click, execute the following function
protected void Submit_Click(object sender, EventArgs e)
{
//Code to be executed
string Userinput; //declare Userinput variable
Userinput = Searchbox.Value; // Set variable to asp controll
Response.Write("<br /> <br />"+ Userinput +" <- user imput works");
ConnectToSql(Userinput);//insert what the user submitted into a query
test();
//
//
//NoTe code validation is needed to prevent injections
//
}
So basically what is happening here is that you are dynamically dropping this onto the page every time the page loads. Because you are doing this dynamically, the checkbox that fires off a "checked" event or is checked against during a postback no longer exists as it is not part of the viewstate. The way that the ASP.NET page lifecycle works is to fire off the sequence of lifecycle events regardless of whether or not the page is posted back or not, meaning that a new page is built upon you firing a postback event and the page goes through preinit, init, preload, load, and all that jazz before it actually hits any of the event handling code. The page that exists for the postback has a freshly created set of checkboxes that have no binding to the ones that were on the previous page.
You have a few options here, and here are two of them:
Have the 'checked' event fire a postback and have the unique ID of the web control checked against a collection you maintain on the server. You can drop the controls onto the page via a repeater or gridview and hook into its populate event. In doing so you can add the unique ID of the control that was just added into a Dictionary that you store in session that maintains any relationship that you want from a checkbox to a piece of data.
Use Javascript to update a hidden field that is always on the page and has view state enabled. In doing so you can have some sort of delimited string containing the information you deem relevant to the 'checked' checkboxes. Every time a checkbox is checked, add its identifying information to the hidden input field's value and then when the postback fires you should be able to check that hidden input for its value and do whatever you need to do from there.
These both seem like pretty hairy ways of handling this though. If you elaborate on what exactly you need then perhaps I can give you a better suggestion.
add the check boxes to the page before the view state is loaded and the event fires. Do it in the OnInit method not the onload. Use Onload to see if they're checked or not. Be sure you're giving them ID's. Unless this is a partial postback (ajax) then only render the check boxes if !IsPostback
It appears after two days of searching, i have found a pretty good solution that is much quicker and easier to understand than some others; It appears that as the other answers state, it is because of the page_load, however in this situation init is not needed, you simply need to recreate all of the controls before you can do anything else.
The key to this solution is:
protected void RecreatePreviousState()
{
if (this.IsPostBack)
{
//code to recreate
}
}
Where the comment in the above code is, is where you call the main function that creates all of your controls, like in my example it was:
ConnectToSql(Searchbox.Value)
below will be all of the code associated with this page, for future reference for anyone with this problem.
Code Behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
public partial class codebehind : System.Web.UI.Page
{
//DECLARATIONS
string selectedvalue;
List<string> createdckbxs = new List<string>();
List<string> CheckedCheckboxes = new List<string>();
CheckBox ckbx;
int ckbxID = 0;
//END DECLARATIONS
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(DateTime.Now); //local time -- testing
Response.Write("<br /><br />NOTE: the id feild in the below table will be useless soon, it is only for testing purposes, look at CRM<br /><br />");
selectedvalue = Request.QueryString["filter"];
//88888888888888888
RecreatePreviousState();
//88888888888888888
Response.Write(selectedvalue);
instructionsfunc();
}
protected void instructionsfunc()
{
switch (selectedvalue)
{
case "Name":
instructions.Text = "Please enter the first few letters of the company you are looking for, ex. for "some company", you might search som";
break;
case "State":
instructions.Text = "Please enter the abreviation of the state you are looking for, ex. for New York, enter NY";
break;
}
}
protected string sqlSelector(string uinput)
{
switch (selectedvalue) //create the sql statments
{
case "Name":
return "SELECT [id],[name] FROM [asd].[jkl] WHERE [name] LIKE '" + uinput + "%' and [deleted] = 0 ORDER BY [name] ASC";
case "State":
return "SELECT [id],[name] FROM [asd].[jkl] WHERE [shipping_address_state] LIKE '" + uinput + "%' and [deleted] = 0 ORDER BY [name] ASC";
default:
Response.Redirect("errorpage.aspx?id=002");
return null;
}
}
//on Submit button click, execute the following function NOTE THIS BUTTON's ONLY USE IS POSTBACK
protected void Submit_Click(object sender, EventArgs e)
{
string Userinput; //declare Userinput variable
Userinput = Searchbox.Value; // Set variable to asp controll
Response.Write("<br /> <br />"+ Userinput +" <- user imput works");
}
//on Clear button click execute the following function
protected void Clear_Click(object sender, EventArgs e)
{
Response.Redirect(Request.RawUrl);
}
protected void ConnectToSql(string input)
{
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
//Todo add any aditional data needed to connection
conn.ConnectionString = ConfigurationManager.ConnectionStrings["SplendidTestConnectionString"].ConnectionString;
try
{
conn.Open();
//this is the actual sql, this gets the data
SqlCommand sqlString2 = new SqlCommand();
sqlString2.CommandText = sqlSelector(input);
sqlString2.CommandTimeout = 15;
sqlString2.CommandType = System.Data.CommandType.Text;
sqlString2.Connection = conn;
SqlDataReader reader;
reader = sqlString2.ExecuteReader();
table_builder(reader);
reader.Close(); //close the sql data reader
}
catch (Exception e)
{
//Some sort of redirect should go here to prevent the user from vewing a broken page
conn.Close();
//Response.Redirect("errorpage.aspx?id=001");
Response.Write(e);
}
finally
{
if (conn.State != System.Data.ConnectionState.Closed)
{
conn.Close();//close up the connection after all data is done being populated
}
}
}
protected void table_builder(SqlDataReader readerinfo)
{
//Create a new step for the user
step3label.Text = "3.";
//Table header
TableHeaderRow hr = new TableHeaderRow();
TableHeaderCell hc = new TableHeaderCell();
TableHeaderCell hc2 = new TableHeaderCell();
TableHeaderCell hc3 = new TableHeaderCell();
hr.Cells.Add(hc);
hc.Text = "ID"; //Assign header 1 with a name
hr.Cells.Add(hc2);
hc2.Text = "Name";//Assign header 2 with a name
hr.Cells.Add(hc3);
hc3.Text = "Selection";
Table1.Rows.Add(hr);
//Dynamic Table Generation
int numcells = 3;
int triswitch = 0;//this is use to chose which cell is made, id, name or selection
while (readerinfo.Read()) //execute the following aslong as there is data to fill the table with
{
for (int j = 0; j < 1; j++)
{
TableRow r = new TableRow();
for (int i = 0; i < numcells; i++)
{
TableCell c = new TableCell();
switch (triswitch)
{
case 0: // this case sets the info for the feild id
c.Text = readerinfo.GetSqlGuid(0).ToString();
//RENAME THIS To ADDING BUTTON = readerinfo.GetSqlGuid(0).ToString();
r.Cells.Add(c);
triswitch = 1;
break;
case 1:
c.Text = readerinfo.GetString(1);
r.Cells.Add(c);
triswitch = 2;
break;
case 2:
ckbx = new CheckBox();
ckbx.ID = "CBX" + ckbxID;
createdckbxs.Add(ckbx.ID);
c.Controls.Add(ckbx);
r.Cells.Add(c);
triswitch = 0;
ckbxID++;
break;
}
}
Table1.Rows.Add(r);
}
}
}
//
//AFTER DATATABLE IS LOADED
//
protected void RecreatePreviousState()
{
if (this.IsPostBack)
{
ConnectToSql(Searchbox.Value);
MergeBtnCreate();
}
}
protected void MergeBtnCreate()
{
Button MergeBTN = new Button();
MergeBTN.Text = "Merge";
MergeBTN.Click += new EventHandler(MergeBTN_Click);
MergeBTNHolder.Controls.Add(MergeBTN);
}
void MergeBTN_Click(object sender, EventArgs e)
{
foreach(string id in createdckbxs)
{
CheckBox myControl1 = (CheckBox)Table1.FindControl(id);
if (myControl1 != null)
{
if (myControl1.Checked == true)
{
CheckedCheckboxes.Add(id);
}
}
else
{
Response.Redirect("errorpage.aspx?id=003");
}
}
}
}
Asp.net
<%# Page Language="C#" AutoEventWireup="true" CodeFile="codebehind.aspx.cs" Inherits="codebehind" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Hello</title>
</head>
<body>
<form id="form1" runat="server">
<div style="background-color:#55aaff;margin-bottom:10px;padding:5px;">
<h3 style="padding:2px;margin:0px;">
2.
</h3>
<asp:Label ID="instructions" runat="server" />
<asp:Label ID="buttonclicked" runat="server" />
<br />
<input id="Searchbox" type="text" runat="server" />
<br />
<asp:Button ID="SubmitBTN" runat="server" OnClick="Submit_Click" Text="Submit" />
<asp:Button ID="ClearBTN" runat="server" OnClick="Clear_Click" Text="Clear" />
</div>
<div>
<h3 style="padding:2px;margin:0px;">
<asp:Label ID="step3label" runat="server" Text=""></asp:Label>
</h3>
<asp:Table ID="Table1" runat="server" GridLines="Both" />
</div>
<div>
<asp:PlaceHolder ID="MergeBTNHolder" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
</html>
Related
I have a problem with asp.net event system.
As the page is being loaded for the first time, a DropDownList is being populated and that's it. On the list SelectedIndexChange the page does a page postback and loads some more info, dynamically creating buttons for it based on some data taken out from the DB.
And at this point all works as expected, the CustomDivs are created and displayed correctly. The problems happens when i click on one of the dynamically created buttons, the page does the postback, goes trouhg the page load but never enters the method of the button that was clicked.
Looking around in the internet i read something about event handlers must be created in the Page_Load method to registered. So i even modified the code behind so that the CaricaPostazioni() method would be fired in the Page_Load, but that did not work. I also tried some other stuff like AutoPostBack property or UseSubmitBheaviour or CausesValidation but nothing seems to work as expected.
I should say that this page is a content page of master page that does absolutely nothing in it's Page_Load()
Any one can help me in this matter? Thank you very much!
Here is the code behind of assegnapostazione.aspx
using Industry4_camerana_gruppo1.App_Code;
using Industry4_camerana_gruppo1.App_Code.Dao;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Industry4_camerana_gruppo1 {
public partial class assegnapostazione : System.Web.UI.Page {
static List Macchinisti = null;
protected void Page_Load(object sender, EventArgs e) {
if (Macchinisti == null) {
Macchinisti = new daoUtente().GetByRuolo("macchinista");
drp_Macchinisti.Items.Add(new ListItem("Seleziona...", "-1"));
foreach (Utente U in Macchinisti) {
drp_Macchinisti.Items.Add(new ListItem(U.Username, U.ID.ToString()));
}
}
}
public void CaricaPostazioni() {
//if (drp_Macchinisti.SelectedValue == "-1") return;
int IDUtente = Convert.ToInt32(drp_Macchinisti.SelectedItem.Value);
List Postazioni = new daoPostazioni().GetAll();
Dictionary Relazioni = new daoPostazioni().GetUtentePostazioni(IDUtente);
if (Postazioni != null) {
Panel row = new Panel();
row.CssClass = "row";
int i = 0;
foreach (Postazione p in Postazioni) {
if (i % 4 == 0) {
pnl_Postazioni.Controls.Add(row);
row = new Panel();
row.CssClass = "row";
}
if (Relazioni.ContainsKey(p.ID)) {
row.Controls.Add(CustomDiv(p, IDUtente, true));
} else {
row.Controls.Add(CustomDiv(p, IDUtente, false));
}
i++;
}
pnl_Postazioni.Controls.Add(row);
}
}
public Panel CustomDiv(Postazione P, int IDUtente, bool Assegnato) {
//
//
//
//
// Foratura
//
//
//
Panel wrapper = new Panel();
wrapper.CssClass = "col";
Panel card = new Panel();
card.CssClass = "card text-center postazione form-group";
Image img = new Image();
img.CssClass = "mx-auto d-block width-70";
img.ID = "btn_" + P.ID;
img.ImageUrl = "~/imgs/ic" + P.Tipo + ".png";
Panel cardTitle = new Panel();
cardTitle.CssClass = "card-title";
Label title = new Label();
title.Text = P.Tipo.ToUpper() + " - " + P.Tag;
Button btn = new Button();
//btn.ID = "btn_" + P.ID + IDUtente;
btn.Attributes.Add("PID", P.ID.ToString());
btn.Attributes.Add("UID", IDUtente.ToString());
//btn.UseSubmitBehavior = true;
if (Assegnato) {
btn.Click += new EventHandler(btn_Rimuovi_Click);
//btn.Click += delegate {
// btn_Rimuovi_Click(btn, null);
//};
btn.CssClass = "btn btn-warning mx-auto form-control";
btn.Text = "Rimuovi";
} else {
btn.Click += new EventHandler(btn_Assegna_Click);
//btn.Click += delegate {
// btn_Assegna_Click(btn, null);
//};
btn.CssClass = "btn btn-success mx-auto form-control";
btn.Text = "Assegna";
}
card.Controls.Add(img);
cardTitle.Controls.Add(title);
card.Controls.Add(cardTitle);
card.Controls.Add(btn);
wrapper.Controls.Add(card);
return wrapper;
}
protected void drp_Macchinisti_SelectedIndexChanged(object sender, EventArgs e) {
CaricaPostazioni();
}
protected void btn_Rimuovi_Click(object sender, EventArgs e) {
Button btn = (Button)sender;
new daoPostazioni().AddRelazione(Convert.ToInt32(btn.Attributes["UID"]), Convert.ToInt32(btn.Attributes["PID"]));
}
protected void btn_Assegna_Click(object sender, EventArgs e) {
Button btn = (Button)sender;
new daoPostazioni().DeleteRelazione(Convert.ToInt32(btn.Attributes["UID"]), Convert.ToInt32(btn.Attributes["PID"]));
}
}
}
Well, I have an answer for you but I don't think you are going to like it.
Due to the stateless nature of webforms, any controls that you add dynamically to a form on a postback will also need to be added back to the page and have it's server events rebound during the OnInit event.
I've created a minimal example that can demonstrate what's going on with this behavior so you can better understand what's happened.
ButtonTest.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ButtonTest.aspx.cs" Inherits="ButtonTest.ButtonTest" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form runat="server">
<asp:Panel runat="server" ID="ButtonPanel">
<asp:Button runat="server" ID="ButtonAdd" OnClick="ButtonAddClick" Text="Click Me"></asp:Button>
</asp:Panel>
</form>
</body>
</html>
And the code behind:
ButtonTest.aspx.cs
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
namespace ButtonTest
{
public partial class ButtonTest : System.Web.UI.Page
{
static List<Button> buttons = new List<Button>();
static bool allowItToWork = true;
protected override void OnInit(EventArgs e)
{
if(Page.IsPostBack && allowItToWork)
{
foreach (var button in buttons)
{
button.Click += ButtonAddClick; // Comment me out and added button's will do nothing when clicked.
ButtonPanel.Controls.Add(button);
}
}
}
protected void ButtonAddClick(object sender, EventArgs e)
{
var button = new Button();
button.Click += ButtonAddClick;
button.Text = "Click Me Too";
buttons.Add(button);
ButtonPanel.Controls.Add(button);
}
}
}
You can toggle between desirable and undesirable behavior by changing the value of the allowItToWork boolean.
When it's set to true, the OnInit overload is adding all buttons back onto the page, as well as applying their event handlers again, because those handlers seem to be lost during the PostBack (unsure on why this happens.) You can click away and new buttons will be added onto the form forever and ever.
When it's set to false, the added button will appear whenever you click the initial button, but it won't fire an event handler as it's no longer bound, and clicking the original button repeatably won't continue to add additional buttons, you'll only ever see a single one, and that one will disappear on PostBack if clicked.
So, the end result of this is essentially that you're stuck reconstructing the whole shebang in the OnInit event.
I am trying to code a survey application which requires text boxes to be added and removed dynamically. I managed to create text boxes dynamically on button click but I'm trying to find out how to removed the text boxes dynamically. Currently the delete functions works well only if I remove text boxes starting from the last. When I try deleting any text boxes in the middle followed by a delete of the last text box, a blank text box is created instead. I'm new to programming and am unsure if this is the best method to use. Also, I would like to find out if it is possible to nest text boxes(allow users to add options to their multi choice questions) to created text boxes and retrieve values inside later.
Code behind:
public partial class Dynamic_Form : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < TotalNumberAdded; ++i)
{
AddQuestion(i + 1);
}
}
protected int TotalNumberAdded
{
get { return (int)(ViewState["TotalNumberAdded"] ?? 0); }
set { ViewState["TotalNumberAdded"] = value; }
}
protected void btn_add_Click(object sender, EventArgs e)
{
TotalNumberAdded++;
AddQuestion(TotalNumberAdded);
}
private void AddQuestion(int controlNumber)
{
Panel newquestion = new Panel();
newquestion.ID = "Panel_" + controlNumber;
TextBox questionbox = new TextBox();
questionbox.ID = "Question_" + controlNumber;
questionbox.Text = "Question";
Button BtnDelete = new Button();
BtnDelete.ID = "BtnDelete_" + controlNumber;
BtnDelete.Text = "Delete"+ controlNumber;
BtnDelete.Click += delete_Click;
DropDownList DDLType = new DropDownList();
DDLType.ID = "DDLType_" + controlNumber;
DDLType.Items.Insert(0, new ListItem("TextField", ""));
DDLType.Items.Insert(1, new ListItem("Multiple Choice", ""));
//add controls
questions.Controls.Add(newquestion);
newquestion.Controls.Add(questionbox);
newquestion.Controls.Add(DDLType);
newquestion.Controls.Add(BtnDelete);
}
private void delete_Click(object sender,EventArgs e)
{
Button btn = (Button)sender;
Control control = btn.Parent;
if (questions.Controls.Contains(control))
{
questions.Controls.Remove(control);
control.Dispose();
TotalNumberAdded--;
Response.Write("Number of Questions:" + TotalNumberAdded);
}
}
}
Html file:
<body>
<form id="form1" runat="server">
<div>
<h1>Test Form</h1>
<asp:Button ID="btn_add" runat="server" Text="Add" OnClick="btn_add_Click" />
</div>
<div id="questions" runat="server">
</div>
</form></body>
.
#Aaron Yong, You can do these scenarios from client side using jQuery or javascript too. I have given below code to achieve what you want from server side.
private void delete_Click(object sender,EventArgs e)
{
Button btn = (Button)sender;
Control control = btn.Parent;
if (questions.Controls.Contains(control))
{
TotalNumberAdded--;
questions.Controls.Clear();
for (int i = 0; i < TotalNumberAdded; ++i)
{
AddQuestion(i + 1);
}
Response.Write("Number of Questions:" + TotalNumberAdded);
}
}
You want to recreate controls again, i have added for loop and removed some code in delete click event, then you will achieve.
As i have given above answer, you can also remove below code from previous answered.
questions.Controls.Remove(control);
control.Dispose();
You will get exact answer
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 found the tutorial to create a dynamic table and add rows:
http://geekswithblogs.net/dotNETvinz/archive/2009/06/29/faq-dynamically-adding-rows-in-asp-table-on-button-click.aspx
How can I read all rows in the table, and then the values of the textbox in the cells? The values are entered in a table in a database (SQL Server).
Can I continue to use C# and asp.net or do I have to use Javascript?
I hope someone will give me help.
This is the code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Dynamic Adding of Rows in ASP Table Demo</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Add New Row" />
</form>
</body>
</html>
CODE BEHIND:
public partial class _Default1 : System.Web.UI.Page
{
//A global variable that will hold the current number of Rows
//We set the values to 1 so that it will generate a default Row when the page loads
private int numOfRows = 1;
protected void Page_Load(object sender, EventArgs e)
{
//Generate the Rows on Initial Load
if (!Page.IsPostBack)
{
GenerateTable(numOfRows);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (ViewState["RowsCount"] != null)
{
numOfRows = Convert.ToInt32(ViewState["RowsCount"].ToString());
GenerateTable(numOfRows);
}
}
private void SetPreviousData(int rowsCount, int colsCount)
{
Table table = (Table)Page.FindControl("Table1");
if (table != null)
{
for (int i = 0; i < rowsCount; i++)
{
for (int j = 0; j < colsCount; j++)
{
//Extracting the Dynamic Controls from the Table
TextBox tb = (TextBox)table.Rows[i].Cells[j].FindControl("TextBoxRow_" + i + "Col_" + j);
//Use Request objects for getting the previous data of the dynamic textbox
tb.Text = Request.Form["TextBoxRow_" + i + "Col_" + j];
}
}
}
}
private void GenerateTable(int rowsCount)
{
//Creat the Table and Add it to the Page
Table table = new Table();
table.ID = "Table1";
Page.Form.Controls.Add(table);
//The number of Columns to be generated
const int colsCount = 3;//You can changed the value of 3 based on you requirements
// Now iterate through the table and add your controls
for (int i = 0; i < rowsCount; i++)
{
TableRow row = new TableRow();
for (int j = 0; j < colsCount; j++)
{
TableCell cell = new TableCell();
TextBox tb = new TextBox();
// Set a unique ID for each TextBox added
tb.ID = "TextBoxRow_" + i + "Col_" + j;
// Add the control to the TableCell
cell.Controls.Add(tb);
// Add the TableCell to the TableRow
row.Cells.Add(cell);
}
// And finally, add the TableRow to the Table
table.Rows.Add(row);
}
//Set Previous Data on PostBacks
SetPreviousData(rowsCount, colsCount);
//Sore the current Rows Count in ViewState
rowsCount++;
ViewState["RowsCount"] = rowsCount;
}
}
Since you're creating the table dynamically, you can't reference it like controls that are statically embedded on the page. To get a reference to the Table object you'll need to find it in the Page's ControlCollection and cast it out, just like in the example:
Table table = (Table)Page.FindControl("Table1");
The Table class contains a table row collection which you will then need to loop over. Each row in the row collection has a collection of cells, each of which will contain child controls (see: Controls property) which will be your textboxes.
Hi if you take look at SetPreviousData this function is trying to read previous textbox value but there is some thing wrong with it i have done following changes and it works fine
first of all the following code in SetPreviousData
Table table = (Table)Page.FindControl("Table1");
is always returning NULL because this function is not a recursive function and your table may be inside a container in your page so add following function to your code
private Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
{
return root;
}
foreach (Control c in root.Controls)
{
Control t = FindControlRecursive(c, id);
if (t != null)
{
return t;
}
}
return null;
}
and change the code
Table table = (Table)Page.FindControl("Table1");
to
Table table = FindControlRecursive(Page , "Table1") as Table;
in next step change the following code in SetPreviousData
tb.Text = Request.Form["TextBoxRow_" + i + "Col_" + j];
to
tb.Text = Request.Form[tb.UniqueID];
set break points and see the results if it's tough to you let me know to provide you a function which returns table data in a datatable
I think you must bind your table again at the Page_load event.For example if you are binding the table at View_Click button event,you have to call this method in Page_load event as View_Click(null,null).
<script type="text/javascript">
var StringToSend='';
function fncTextChanged(newvalueadded) {
if (StringToSend != '')
StringToSend = StringToSend + ';' + newvalueadded;
else
StringToSend = newvalueadded;
//alert(StringToSend); -- For Testing all values
// now store the value of StringToSend into hidden field ---- HFTEXTVALUES to access it from server side.
}
</script>
<asp:Button ID="Save" runat="server" onclick="SaveTextBoxValues_Click" Text="save" />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Add New Row" />
<asp:HiddenField ID="hfTextValues" runat="server" Visible="false" Value="" />
Server Side :
protected void Page_Load(object sender, EventArgs e)
{
//Generate the Rows on Initial Load
if (!Page.IsPostBack)
{
GenerateTable(numOfRows);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (ViewState["RowsCount"] != null)
{
numOfRows = Convert.ToInt32(ViewState["RowsCount"].ToString());
GenerateTable(numOfRows);
}
}
protected void SaveTextBoxValues_Click(object sender, EventArgs e)
{
string AllTextBoxValues = hfTextValues.Value;
string[] EachTextBoxValue = AllTextBoxValues.Split('~');
//here you would get all values, EachTextBoxValue[0] gives value of first textbox and so on.
}
private void GenerateTable(int rowsCount)
{
//Creat the Table and Add it to the Page
Table table = new Table();
table.ID = "Table1";
Page.Form.Controls.Add(table);
//The number of Columns to be generated
const int colsCount = 3;//You can changed the value of 3 based on you requirements
// Now iterate through the table and add your controls
for (int i = 0; i < rowsCount; i++)
{
TableRow row = new TableRow();
for (int j = 0; j < colsCount; j++)
{
TableCell cell = new TableCell();
TextBox tb = new TextBox();
HiddenField hf = new HiddenField();
// Set a unique ID for each TextBox added
tb.ID = "tb" + i + j;
hf.ID = "hf" + i + j;
tb.Attributes.Add("onblur", "fncTextChanged(this.value);");
// Add the control to the TableCell
cell.Controls.Add(tb);
// Add the TableCell to the TableRow
row.Cells.Add(cell);
}
// And finally, add the TableRow to the Table
table.Rows.Add(row);
}
}
Let me know if you have any questions.
One more thing, if you wish to store the values and retrieve them later, the code would be modified accordingly.
reference for a dynamic table doesn't work well , blame microsoft ,
I use this :
Save inside a session List[YourObjectData] and every time you get into Page_Load , fill it the table
here is solution for number 2 :
somewhere inside Default.aspx
<div class="specialTable">
<asp:Table ID="Table1" runat="server" />
</div>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
FillDynamicTable();
if (!IsPostBack)
{
}
}
private void FillDynamicTable()
{
Table1.Rows.Clear(); // Count=0 but anyways
if (Session["Table1"] == null) return;
foreach (var data in Session["Table1"] as List<MyObject>)
{
AddRow(data);
}
}
private void AddRow(MyObject data)
{
var row = new TableRow { Height = 50 };
var cell = new TableCell();
var label = new Label { Text = data.something, Width = 150 };
cell.Controls.Add(label);
row.Cells.Add(cell);
Table1.Rows.Add(row);
}
I'm using PostBackUrl to post my control from a "firstwebpage.aspx" to a "secondwebpage.aspx" so that I would be able to generate some configuration files.
I do understand that I can make use of PreviousPage.FindControl("myControlId") method in my secondwebpage.aspx to get my control from "firstwebpage.aspx"and hence grab my data and it worked.
However, it seems that this method does not work on controls which I generated programmically during runtime while populating them in a table in my firstwebpage.aspx.
I also tried using this function Response.Write("--" + Request["TextBox1"].ToString() + "--");
And although this statement do printout the text in the textfield on TextBox1, it only return me the string value of textbox1. I am unable to cast it to a textbox control in the following format too
TextBox temptextBox = (TextBox)Request["TextBox1"];
My question is, how can I actually access the control which i generated programmically in "firstwebpage.aspx" on "secondwebpage.aspx"?
Please advice!
thanks alot!
//my panel and button in aspx
<asp:Panel ID="Panel2" runat="server"></asp:Panel>
<asp:Button ID="Button1" runat="server" Text="Generate Xml" PostBackUrl="~/WebForm2.aspx" onclick="Button1_Click" />
//this is my function to insert a line into the panel
public void createfilerow(string b, string path, bool x86check, bool x86enable, bool x64check, bool x64enable)
{
Label blank4 = new Label();
blank4.ID = "blank4";
blank4.Text = "";
Panel2.Controls.Add(blank4);
CheckBox c = new CheckBox();
c.Text = b.Replace(path, "");
c.Checked = true;
c.ID = "1a";
Panel2.Controls.Add(c);
CheckBox d = new CheckBox();
d.Checked = x86check;
d.Enabled = x86enable;
d.ID = "1b";
Panel2.Controls.Add(d);
CheckBox e = new CheckBox();
e.Checked = x64check;
e.Enabled = x64enable;
e.ID = "1c";
Panel2.Controls.Add(e);
}
//my virtual path in WebForm2.aspx
<%# PreviousPageType VirtualPath="~/WebForm1.aspx" %>
//my pageload handler
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
CheckBox tempCheckbox = (CheckBox)Page.PreviousPage.FindControl("1a");
Button1.Text = tempCheckbox.Text;
}
}
//handler which will populate the panel upon clicking
protected void Button7_Click(object sender, EventArgs e)
{
//get foldername
if (!Directory.Exists(#"myfilepath" + TextBox2.Text))
{
//folder does not exist
//do required actions
return;
}
string[] x86files = null;
string[] x64files = null;
string[] x86filespath = null;
string[] x64filespath = null;
ArrayList common = new ArrayList();
if (Directory.Exists(#"myfilepath" + TextBox2.Text + "\\x86"))
x86files = Directory.GetFileSystemEntries("myfilepath" + TextBox2.Text + "\\x86");
if (Directory.Exists(#"myfilepath" + TextBox2.Text + "\\x64"))
x64files = Directory.GetFileSystemEntries("myfilepath" + TextBox2.Text + "\\x64");
//some codes to convert x64files and x86files to string[]
//The header for Panel, 4 column
Label FL = new Label();
FL.ID = "flavourid";
FL.Text = "Flavour";
Panel2.Controls.Add(FL);
Label filetext = new Label();
filetext.ID = "filenamelabel";
filetext.Text = "File(s)";
Panel2.Controls.Add(filetext);
Label label86 = new Label();
label86.ID = "label86";
label86.Text = "x86";
Panel2.Controls.Add(label86);
Label label64 = new Label();
label64.ID = "label64";
label64.Text = "x64";
Panel2.Controls.Add(label64);
//a for loop determine number of times codes have to be run
for (int a = 0; a < num; a++)
{
ArrayList location = new ArrayList();
if (//this iteration had to be run)
{
string path = null;
switch (//id of this iteration)
{
case id:
path = some network address
}
//check the current version of iternation
string version = //version type;
//get the platform of the version
string platform = //platform
if (curent version = certain type)
{
//do what is required.
//build a list
}
else
{
//normal routine
//do what is required
//build a list
}
//populating the panel with data from list
createflavourheader(a);
//create dynamic checkboxes according to the list
foreach(string s in list)
//createrow parameter is by version type and platform
createfilerow(readin, path, true, true, false, false);
}
}
}
form1.Controls.Add(Panel2);
}
Sorry can't show you the full code as it is long and I believe it should be confidential even though i wrote them all
Yes you can access, Below is an example
// On Page1.aspx I have a button for postback
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
PostBackUrl="~/Page2.aspx" />
// Page1.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
TextBox t = new TextBox(); // created a TextBox
t.ID = "myTextBox"; // assigned an ID
form1.Controls.Add(t); // Add to form
}
Now on the second page I will get the value of TextBox as
// Page2.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
TextBox t = (TextBox) PreviousPage.FindControl("myTextBox");
string mytboxvalue = t.Text;
}
// OR
string myTextBoxValue = Request.Form["myTextBox"];
}
Updated Answer:
Panel myPanel = new Panel();
myPanel.ID = "myPanel";
TextBox t = new TextBox();
t.ID = "myTextBox";
myPanel.Controls.Add(t);
TextBox t1 = new TextBox();
t1.ID = "myTextBox1";
myPanel.Controls.Add(t1);
// Add all your child controls to your panel and at the end add your panel to your form
form1.Controls.Add(myPanel);
// on the processing page you can get the values as
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
TextBox t = (TextBox) PreviousPage.FindControl("myTextBox");
string mytboxvalue = t.Text;
}
string myTextBoxValue = Request.Form["myTextBox1"];
}
I also tried using this function Response.Write("--" +
Request["TextBox1"].ToString() + "--"); And although this statement do
printout the text in the textfield on TextBox1, it only return me the
string value of textbox1. I am unable to cast it to a textbox control
in the following format too
TextBox temptextBox = (TextBox)Request["TextBox1"];
Hi lw,
I think you may try passing the type of control (e.g. 'tb') together with the content and creating a new object (e.g. TextBox) and assign it to templtexBox object.
My 20 cents.
Andy