Using PostBackUrl, Getting PreviousPage.Control() - c#

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

Related

Recreating many dynamic controls in ASP NET (individually actions)

I have problem with ASP.NET and dynamic controls. I have three ASCX. One of them creates two textboxes and some labels. The second containing control created if first ASCX (two textboxes and some labels). In addiction, second control also have link button named “Add Next” which on click event adding another control (two textboxes and some labels). The third ASCX control contains many the second ASCX (amount depend on SQL result). I made simple image to clarify:
The orange box contains many controls. The red box adding many black boxes on click “ADD NEXT”.
For now I use session variable to save state during recreate. For one “red box” it is working, but if I add more “red boxes”, clicking every “ADD NEXT” adding new control with textboxes and labels to every “red box” instead of in this where was clicked button “ADD NEXT”. I suppose why it is happening. Because every “red box” refers to the same Session variable, but I don’t know how to fix it. I was trying during OnClick event passing unique ID and setting this ID as session variable name, but it wasn’t working as I expected.
Could you tell me, how to manage it? How looks the best way to recreate controls, how I can manage controls individually? If something is not clear, I will clarify. Always I was finding answers in stackoverflow, but this problem has outgrow me.
Best wishes.
(Sorry for my English, it doesn’t my native language)
My code.
Code for creating textboxes and some labels (Calculator.cs):
public string FLong
{
get
{
object o = ViewState["FLong"];
if (o == null)
return String.Empty;
return (string)o;
}
set { ViewState["FLong"] = value; }
}
public string FWide
{
get
{
object o = ViewState["FWide"];
if (o == null)
return String.Empty;
return (string)o;
}
set
{
ViewState["FWide"] = value;
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
CreateControlHierarchy();
ClearChildViewState();
}
protected virtual void CreateControlHierarchy()
{
Literal row = new Literal();
row.Text = "<div class='row surface'>";
Controls.Add(row);
//Add new TextBox;
Literal col = new Literal();
col.Text = "<div class='col-xs-4'>";
Controls.Add(col);
TextBox fLong = new TextBox();
fLong.ID = "fLong";
fLong.CssClass = "form-control";
//fLong.TextChanged += new EventHandler(Calculate_TextChanged);
//fLong.AutoPostBack = true;
fLong.Text = FLong;
Controls.Add(fLong);
Literal textLong = new Literal();
textLong.Text = "<span>ft. long x</span>";
Controls.Add(textLong);
RegularExpressionValidator flongValidate = new RegularExpressionValidator();
flongValidate.ControlToValidate = "fLong";
flongValidate.ErrorMessage = "Only Numbers allowed";
flongValidate.ValidationExpression = #"\d+";
flongValidate.ForeColor = System.Drawing.Color.Red;
flongValidate.Attributes["style"] = "display:block";
Controls.Add(flongValidate);
Literal colEnd = new Literal();
colEnd.Text = "</div>";
Controls.Add(colEnd);
//Add new Textbox
Literal col2 = new Literal();
col2.Text = "<div class='col-xs-4'>";
Controls.Add(col2);
TextBox fWide = new TextBox();
fWide.ID = "fWide";
fWide.CssClass = "form-control";
fWide.Text = FWide;
Controls.Add(fWide);
Literal textWide = new Literal();
textWide.Text = "<span>ft. wide</span>";
Controls.Add(textWide);
RegularExpressionValidator fwideValidate = new RegularExpressionValidator();
fwideValidate.ControlToValidate = "fWide";
fwideValidate.ErrorMessage = "Only Numbers allowed";
fwideValidate.ValidationExpression = #"\d+";
fwideValidate.ForeColor = System.Drawing.Color.Red;
fwideValidate.Attributes["style"] = "display:block";
Controls.Add(fwideValidate);
Literal col2End = new Literal();
col2End.Text = "</div>";
Controls.Add(col2End);
Literal rowEnd = new Literal();
rowEnd.Text = "</div>";
Controls.Add(rowEnd);
}
Code handling recreating (SurfaceCalculator.cs):
private int DefaultAmountControls = 1;
private string surfaceID;
public string SurfaceID
{
get { return surfaceID; }
set { surfaceID = value; }
}
public int Visibility
{
get
{
//store the object in session if not already stored
if (Session[surfaceID] == null)
Session[surfaceID] = DefaultAmountControls;
//return the object from session
return (int)Session[surfaceID];
}
set
{
if (value <= 5)
Session[surfaceID] = value;
else
Session[surfaceID] = 5;
}
}
protected void addSurface_Click(object sender, EventArgs e)
{
LinkButton b = (LinkButton)sender;
surfaceID = b.CommandArgument;
Visibility += 1;
}
protected override void OnInit(EventArgs e)
{
LinkButton addSurface = new LinkButton();
addSurface.Text = "+ Add surface";
addSurface.CommandArgument = surfaceID;
addSurface.Click += new EventHandler(addSurface_Click);
base.OnInit(e);
List<Calculator> c = Surface.Controls.OfType<Calculator>().ToList();
for (int i = 1; i <= Visibility; i++)
{
c.ElementAt(i - 1).Visible = true;
}
if (Visibility >= 5)
{
addSurface.Enabled = false;
}
Controls.Add(addSurface);
}
Code to adding many controls depending on SQL result
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
var listOfProjects = //GETTING FROM SQL
if(listOfProjects != null)
{
foreach (var proj in listOfProjects)
{
Panel placeHolder = new Panel();
placeHolder.CssClass = "surface";
placeHolder.ID = "placeHolder" + proj.DocumentID;
surfacesContainer.Controls.Add(placeHolder);
SurfaceCalculator newElement = (SurfaceCalculator)LoadControl("~/PATH_TO/CONTROL.ascx");
newElement.ID = "surfaceCalculator" + proj.DocumentID;
newElement.SurfaceID = newElement.ID;
placeHolder.Controls.Add(newElement);
}
}
}

Read/edit values starting from a Telerik RadGrid

I have this situation:
... a normal RadGrid with data. And, if I clic on a row, I want to obtain this:
... a list of label-textbox pair (please pay attention: these list of data are obtained from the row, but are not part of it).
With the first RadGrid it's all okay.
Therefore, I have used a simple HTML Table for the list of pair (in the second image). This list being generated code-behind, from database.
The problem is the update of the TextBoxs: if I edit these textboxes and do clic on the Update Botton, starts the myRadGrid_UpdateCommand method. But I can't find a way to manage these textboxes (they don't appear in myRadGrid.Controls or else).
So I have tried to use another RadGrid inside the first RadGrid, but with no luck... Maybe I have to use another different Telerik control?
Someone know how I can do this?
This is part of my implementation:
protected void myRadGrid_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
{
this.myRadGrid.DataSource = this.dtListaDettagli;
this.dtListaDettagli.PrimaryKey = new DataColumn[] { this.dtListaDettagli.Columns["key"] };
}
protected void myRadGrid_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
if (e.Item is GridEditFormItem && e.Item.IsInEditMode)
{
GridEditFormItem item = (GridEditFormItem)e.Item;
UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);
var listOfDetails = this.Session["listOfDetails"];
//...
var dtoTrav = (List<Detail_Type_N>) listOfDetails;
PopolaUC(dtoTrav, userControl, e.Item.ItemIndex);
}
}
private void PopolaUC<T>(List<T> data, UserControl uc, int index) where T : FlussiBaseDto
{
// ...
RadPane radPane = uc.FindControl("RadPane1") as RadPane;
var properties = TypeDescriptor.GetProperties(typeof(Detail_Type_N));
// ...
var dettaglioSelected = (from x in data
where x.IdFlusso == idFlussoSelected && x.ProgDettaglio == progDettaglioSelected
select x).FirstOrDefault();
HtmlTable htmlTable = new HtmlTable();
htmlTable.ID = "DettaglioSinistro";
var tRow = new HtmlTableRow();
int i = 0;
foreach (PropertyDescriptor prop in properties)
{
i++;
if (i > 3) // organizza la sottotabella in 2 colonne
{
tRow = new HtmlTableRow();
i = 1;
}
// Set label:
HtmlTableCell tLabel = new HtmlTableCell();
var stringInNormalCase = Regex.Replace(prop.Name, "(\\B[A-Z])", " $1");
tLabel.InnerText = stringInNormalCase;
tRow.Cells.Add(tLabel);
// Set TextBox:
HtmlTableCell tCell = new HtmlTableCell();
// ...
TextBox box = new TextBox();
box.Text = Convert.ToString(prop.GetValue(detailSelected));
box.ID = string.Format("my_{0}", prop.Name);
tCell.Controls.Add(box);
tRow.Cells.Add(tCell);
htmlTable.Rows.Add(tRow);
}
radPane.Controls.Add(htmlTable);
}
protected void myRadGrid_UpdateCommand(object source, GridCommandEventArgs e)
{
GridEditableItem editedItem = e.Item as GridEditableItem;
UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);
//Prepare new row to add it in the DataSource
DataRow[] changedRows = this.dtListaDettagli.Select("key = " + editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["key"]);
// ... and then?
catch (Exception ex)
{
changedRows[0].CancelEdit();
Label lblError = new Label();
lblError.Text = string.Format("Errore nell'aggiornamento movimento. Errore: {0} ", ex.Message);
lblError.ForeColor = System.Drawing.Color.Red;
RadGridIpa.Controls.Add(lblError);
e.Canceled = true;
}
}
You cannot generate TextBoxes and Labels dynamically.
Instead, you want to use Edit Form.
For example,
<telerik:RadGrid ID="RadGrid1" ...>
<MasterTableView>
...
<EditFormSettings>
Place those textboxes and lables here.
</EditFormSettings>
</MasterTableView>
</telerik:RadGrid>

Database Records on Page Load - Dynamic Text Fields

I am working with dynamically created text fields. Most solutions I have found thus far have been related to retaining view state on postback, but I believe I have taken care of that issue. On postback, the values that are in the text fields are retained.
The issue I am having: I can't get the database values currently stored to load in the dynamic fields. I am currently calling loadUpdates() to try to do this, but unsure how to grab the data row, while also making sure I can continue to add new fields (or remove them). How can I achieve this?
"txtProjectsUpdate" is the text field, "hidFKID" is the foreign key to a parent table, and "hidUpdateID" is the hidden value of the primary key in the child table (the values I am attempting to load).
Markup:
<div>
<asp:Button ID="btnAddTextBox" runat="server" Text="Add" OnClick="btnAddTextBox_Click" />
<asp:Placeholder ID="placeHolderControls" runat="server"/>
</div>
<asp:TextBox runat = "server" ID = "hidUpdateID" />
<asp:HiddenField runat = "server" ID = "hidFKID" />
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
for (var i = 0; i < TextBoxCount; i++)
AddTextBox(i);
}
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt = selectDetails();
tryHidFKID(hidFKID, dt.Rows[0]["fkprjNumber"].ToString());
loadUpdates();
}
}
protected void btnAddTextBox_Click(object sender, EventArgs e)
{
AddTextBox(TextBoxCount);
TextBoxCount++;
}
private int TextBoxCount
{
get
{
var count = ViewState["txtBoxCount"];
return (count == null) ? 0 : (int)count;
}
set { ViewState["txtBoxCount"] = value; }
}
private void btnRemove_Click(object sender, EventArgs e)
{
var btnRemove = sender as Button;
if (btnRemove == null) return;
btnRemove.Parent.Visible = false;
}
private void AddTextBox(int index)
{
var panel = new Panel();
panel.Controls.Add(new TextBox
{
ID = string.Concat("txtProjectUpdates", index),
Rows = 5,
Columns = 130,
TextMode = TextBoxMode.MultiLine,
CssClass = "form-control",
MaxLength = 500
});
panel.Controls.Add(new TextBox
{
ID = string.Concat("hidUpdateID", index)
});
var btn = new Button { Text = "Remove" };
btn.Click += btnRemove_Click;
panel.Controls.Add(btn);
placeHolderControls.Controls.Add(panel);
}
protected void loadUpdates()
{
DataTable dt = dbClass.ExecuteDataTable
(
"spSelectRecords", <db>, new SqlParameter[1]
{
new SqlParameter ("#vFKPrjNumber", hidFKID.Value)
}
);
AddTextBox(TextBoxCount);
TextBoxCount++;
}
protected void tryHidFKID(HiddenField hidFKID, string txtSelected)
{
try
{
hidFKID.Value = txtSelected;
}
catch
{
hidFKID.Value = "";
}
}

Dynamic controls disappear ASP.NET C# (Loading controls depending on a DropDownList selection)

I'm new in ASP.NET; I have a DropDownList in a page (with a masterpage):
<asp:DropDownList ID="cmbPrueba" runat="server" OnSelectedIndexChanged="cmbPrueba_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem Value="0">Compresor de Aire</asp:ListItem>
<asp:ListItem Value="1">Compresor/Unidad de Refrigeración</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnActualizar" runat="server" Text="Actualizar" OnClick="btnActualizar_Click" />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
Depending of the DropDownList (cmbPrueba) the placeHolder creates controls using the string array; (I made the string arrays simulating string result of database).
So, if I take itemIndex=0 ("CompresorDeAire) I will create: "TextBox", "Calendar", "TextBox";
if I take index=1 (CompresorUnidadDeRefrigeracion ) the controls are: "DropDownList", "TextBox", "Calendar", "Calendar", "TextBox"... but there is a "DropDownList" control, so I will full it with this info:
private string[] CompresorUnidadDeRefrigeracionTipoCompresor = new string[] { "Compresor Alternativo", "Compresor de Tornillo", "Unidad de Refrigeración" };
And so on. Here is the code:
public partial class Controles : System.Web.UI.Page
{
private Label _Label;
private TextBox _TextBox = new TextBox();
private Calendar _Calendar = new Calendar();
private DropDownList _DropDownList = new DropDownList();
private string[] CompresorDeAire = new string[] { "TextBox", "Calendar", "TextBox" };
private string[] CompresorUnidadDeRefrigeracion = new string[] { "DropDownList", "TextBox", "Calendar", "Calendar", "TextBox" };
private string[] CompresorUnidadDeRefrigeracionTipoCompresor = new string[] { "Compresor Alternativo", "Compresor de Tornillo", "Unidad de Refrigeración" };
private string[] BombaElectrica = new string[] { "TextBox", "TextBox", "TextBox", "TextBox", "TextBox", "TextBox" };
protected void Page_Load(object sender, EventArgs e)
{
LoadInfo(CompresorDeAire);
}
private void LoadInfo(string[] Arreglo)
{
for (int i = 0; i < Arreglo.Length; i++)
{
_Label = new Label();
_TextBox = new TextBox();
_Calendar = new Calendar();
_DropDownList = new DropDownList();
_Label.Text = Arreglo[i].ToString() + i.ToString();
_Label.ID = _Label.Text;
PlaceHolder1.Controls.Add(_Label);
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
if (Arreglo[i] == _TextBox.GetType().Name.ToString())
{
_TextBox.ID = "txt" + _Label.ID;
//_TextBox.AutoPostBack = true;
PlaceHolder1.Controls.Add(_TextBox);
}
else if (Arreglo[i] == _Calendar.GetType().Name.ToString())
{
_Calendar.ID = "cln" + _Label.ID;
PlaceHolder1.Controls.Add(_Calendar);
}
else if (Arreglo[i] == _DropDownList.GetType().Name.ToString())
{
_DropDownList.ID = "cmb" + _Label.ID;
//_DropDownList.AutoPostBack = true;
foreach (var item in CompresorUnidadDeRefrigeracionTipoCompresor)
{
int j = 0;
_DropDownList.Items.Add(item);
j++;
}
PlaceHolder1.Controls.Add(_DropDownList);
}
PlaceHolder1.Controls.Add(new LiteralControl("<br /><br />"));
}
}
protected void cmbPrueba_SelectedIndexChanged(object sender, EventArgs e)
{
txtMensaje.Text = "";
PlaceHolder1.Controls.Clear();
switch (cmbPrueba.SelectedIndex)
{
case 0:
this.LoadInfo(CompresorDeAire);
break;
case 1:
this.LoadInfo(CompresorUnidadDeRefrigeracion);
break;
case 2:
this.LoadInfo(BombaElectrica);
break;
}
}
protected void btnActualizar_Click(object sender, EventArgs e)
{
txtMensaje.Text = "";
for (int i = 0; i < PlaceHolder1.Controls.Count; i++)
{
switch (PlaceHolder1.Controls[i].GetType().Name.ToString())
{
case "TextBox":
TextBox TB = PlaceHolder1.FindControl(PlaceHolder1.Controls[i].ID) as TextBox;
txtMensaje.Text += PlaceHolder1.Controls[i].GetType().Name + " " + PlaceHolder1.Controls[i].ID + " " + TB.Text + "\n";
TB.Text += "*";
break;
case "Calendar":
Calendar Cal = PlaceHolder1.FindControl(PlaceHolder1.Controls[i].ID) as Calendar;
txtMensaje.Text += PlaceHolder1.Controls[i].GetType().Name + " " + PlaceHolder1.Controls[i].ID + " " + Cal.SelectedDate.ToShortDateString() + "\n";
break;
case "DropDownList":
DropDownList DD = PlaceHolder1.FindControl(PlaceHolder1.Controls[i].ID) as DropDownList;
txtMensaje.Text += PlaceHolder1.Controls[i].GetType().Name + " " + PlaceHolder1.Controls[i].ID + " " + DD.Text + "\n";
break;
}
}
}
protected void btnLimpiar_Click(object sender, EventArgs e)
{
PlaceHolder1.Controls.Clear();
txtMensaje.Text = "";
}
}
When I run the code by default is Index = 0 , I use the textbox and calendar, and click "Actualizar" and I can see the info in the text box, when I choose Index=1 (and load the 2nd array) all the new controls show up, but if I choose a date or I write in the textbox and click in the buttom "Actualizar" the page return to the previous page (array 1).
I appreciate your help! thanks.
I am assuming that when you say “the page return to the previous page (array 1).” That you mean the first array (in the zero-th element)
The problem is that .NET will not automatically re-create the dynamic controls for you on the post back. You have to handle that.
Here are the basic steps for the first page request:
Execute the Page_load event, which calls LoadInfo for CompresorDeAir.
Then when you selected a different entry in the dropdown and then click Actualizer button then it does a post back with these basic steps:
Execute the Page_load event, which calls LoadInfo for CompresorDeAir.
Execute cmbPrueba_SelectedIndexChanged which throws away the dynamic controls that were added in the page load and loads the control for the selected index.
Execute btnActualizer_Click event which shows the controls in the dynamic place holder, these being the ones for the selected dropdown value.
Then when you change the text or date and then click Actualizer button it does these steps:
Execute the Page_load event, which calls LoadInfo for CompresorDeAir.
Execute btnActualizer_Click event which shows the controls in the dynamic place holder. In this case the ones from the page load are shown. the controls from the prior selected dropdown list item do not get created.
The only time the controls from the selected item in the dropdown list are added to the place holder is when the selected item changes for the dropdown.
The solution is put a hidden variable in the form to hold the last selected item from the drop down. Everytime the selected index changes then update this hidden value. In the page load event, on a postback, load the appropriate array based on that hidden value.

Grab user input from dynamic text box

I have two buttons. One button that creates the Textbox and another that submits the information. I'm having trouble retrieving the users texts once the textbox has been created. Here is the code:
private void CreateTextBox(int j) //Creates the fields / cells
{
TextBox t = new TextBox();
t.ID = "Textbox" + j;
//t.Text = "Textbox" + j;
lstTextBox.Add(t);
var c = new TableCell();
c.Controls.Add(t);
r.Cells.Add(c);
table1.Rows.Add(r);
Session["test"] = lstTextBox;
}
protected void Button2_Click(object sender, EventArgs e)
{
string[] holder = new string[4];
for (int i = 0; i < holder.Length; i++)
{
holder[i] = "";
}
List<TextBox> lstTextBox = (Session["test"] as List<TextBox>);
if (lstTextBox.Count < Counter)
{
int i = lstTextBox.Count;
for (int j = 0; j < i; j++)
{
holder[j] = lstTextBox[j].Text;
}
SqlConnection conns = new SqlConnection(ConfigurationManager.ConnectionStrings["TestDBConnectionString1"].ConnectionString);
SqlCommand cmd = new SqlCommand("Insert into LoanerForm (field0, field1, field2, field3) Values (#field0, #field1, #field2, #field3)", conns);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#field0", holder[0]);
cmd.Parameters.AddWithValue("#field1", holder[1]);
cmd.Parameters.AddWithValue("#field2", holder[2]);
cmd.Parameters.AddWithValue("#field3", holder[3]);
conns.Open();
cmd.ExecuteNonQuery();
conns.Close();
}
Counter = 0;
Button1.Visible = true; //Going to submit data to SQL
}
Thank you in advance!
Here is how you create TextBoxes dynamically. It keeps track of the number of textboxes in ViewState.
<asp:Button runat="server" ID="Button1" OnClick="Button1_Click"
Text="Create TextBoxes" />
<asp:Button runat="server" ID="Button2" OnClick="Button2_Click"
Text="Save TextBoxes to Database" />
<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
public int Counter
{
get { return Convert.ToInt32(ViewState["Counter"] ?? "0"); }
set { ViewState["Counter"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
// Need to reload those textboxes on page back
// Otherwise, they will becomes null
int total = Counter;
for (int i = 0; i < total; i++)
{
var textBox = new TextBox
{
ID = "TextBox" + i,
Text = "TextBox" + i
};
PlaceHolder1.Controls.Add(textBox);
}
}
private void CreateTextBox(int id)
{
var textBox = new TextBox
{
ID = "TextBox" + id,
Text = "TextBox" + id
};
PlaceHolder1.Controls.Add(textBox);
}
protected void Button1_Click(object sender, EventArgs e)
{
CreateTextBox(Counter);
Counter = Counter + 1;
}
protected void Button2_Click(object sender, EventArgs e)
{
int total = Counter;
for (int i = 0; i < total; i++)
{
var textbox = PlaceHolder1.FindControl("TextBox" + i) as TextBox;
var text = textbox.Text;
// Do something with text
}
}
Don't store the TextBoxes in Session; rather, create them on the page.
The trick is creating them at the right time EVERY time (i.e. with each PostBack). Try loading them OnLoad() for the page (or CreateChildControls() if possible).
Once you do that, ASP.NET will automatically associate the input with the TextBox and you should be able to reference them as you normally would or via .FindControl() of the parent.
I think You used big program for generating dynamic textboxes and inserting into data base.For retriving text from dynamically generated textboxes,use the code below..
Request.Form["Textbox" + i.ToString()]
where "i" represents the number of textboxes you generated.
For more info.Please Check the below link.
how to insert value to sql db from dynamically generated textboxes asp.net

Categories

Resources