 |
|
 |
You should always add your dynamic controls on the PreInit event (or Init, if you're using a MasterPage). You'd lose asp.net theming functionalities otherwise, unless you explicitly call .ApplyStyleSheetSkin() on each added control.
Also, it must be noted that a dynamically added control state cannot be retained at all: try changing the visibility or width of those controls and it won't be retained. That's because it's not the ViewState who's responsible for retaining each control value, try decoding the viewstate value to see no reference to those controls. You could disable it altogether and this example would still work. In reality, it's Asp.net that's doing something else other than parsing and validating a viewstate when a postback occurs. Asp.net enumerates the controls in a page and if any of them implements IPostBackDataHandler, it will call their LoadPostData method passing the Request.Form collection and a collection Key as parameters. The control will then figure out how to set its own value (its Text property if it's a textbox, Checked if it's a checkbox and so on).
So, Labels values are not retained because the Label class doesn't implement IPostBackDataHandler. This is understandable, a Label it's not rendered as a form control.
Check this page (Stage 3 - Load Postback data): http://msdn.microsoft.com/en-us/library/ms972976[^]
|
|
|
|
 |
|
 |
excellent have crawled the web for this problem... this article solved it in minities with understanding.
|
|
|
|
 |
|
 |
Simple clear example that works
|
|
|
|
 |
|
 |
Object reference not set to an instance of an object.
can some1 help me why?
|
|
|
|
 |
|
 |
how can you add a new button to your page by clicking on a add button whitch its events are working fine
|
|
|
|
 |
|
|
 |
|
 |
hi,
it is pointing an error
"Control 'ControlID_0' of type 'TextBox' must be placed inside a form tag with runat=server. "
how to solve it...help me
|
|
|
|
 |
|
 |
hi, and thanks for this useful post.
i have one gridview in my asp.net 2.0 page and i fill it by table dynamically at runtime. i inserted check boxes at the last column to select by user for deleting or editing. but when i press button and page is posted back , selected check boxes have been lost(with their values)...!!
let me to know how can i solve this problem.
with regards, mojtaba madadyar.(madadyar.com)
with regards.
M.Madadyar
|
|
|
|
 |
|
 |
I've been trying for almost 3 days to discover the problem why I cant get the control values after post back.
Here is my code please help me.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class questions : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState.Add("mode", "0");
}
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
if (ViewState["mode"].ToString() == "1")
{
if (TextBox1.Text != "")
{
for (int i = 0; i < int.Parse(TextBox1.Text); i++)
{
CreateControls(i);
}
}
}
}
///
/// Calls the function "CreateControls" which creates a number of controls based on the number eneterd in the TextBox.
///
///
///
protected void BTN_Submit_Click(object sender, EventArgs e)
{
if (TextBox1.Text != "")
{
for (int i = 0; i < int.Parse(TextBox1.Text); i++)
{
CreateControls(i);
}
}
}
///
/// Checks the values entered by the user and calculates the total result.
///
///
///
protected void BTN_Result_Click(object sender, EventArgs e)
{
if (TextBox1.Text != "")
{
for (int i = 0; i < int.Parse(TextBox1.Text); i++)
{
CreateControls(i);
}
}
ViewState.Add("mode", "1");
}
///
/// Creates controls dynamically to the page.
///
protected void CreateControls(int i)
{
ASP.mcq_ascx newc = new ASP.mcq_ascx();
newc.ID = "newc" + i.ToString();
this.Q_PlaceHolder.Controls.Add(newc);
}
}
|
|
|
|
 |
|
 |
I have problem get the checkbox value after post back, there is no problem when generate dynamic control, I just can't get the "true" value after I check the checkbox and hit the ImageButton.
I will get "false" value after I postback even I have the checkbox checked, is that I miss anything?
Thanks for help.
Here is my code:
In Defualt.aspx:
----------------------------------------------------------------------------------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" EnableSessionState="True" EnableViewState="true" %>
<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ImageButton id="AddToCartButton" onclick="AddToCartBtn_Clicked" imageurl="images/btn_addtocart.gif" runat="server" />
<asp:PlaceHolder id="BestDiscountPlaceHolder" visible="false" runat="server" />
</form>
</body>
</html>
------------------------------------------------------------------------------------------------
In default.aspx.cs
------------------------------------------------------------------------------------------------
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Mail;
using System.Web.Security;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label BestDiscountLabel;
protected System.Web.UI.WebControls.CheckBox BestDiscountChkbox;
protected void Page_Load(object sender, EventArgs e)
{
decimal price = Convert.ToDecimal(99.99);
BestDiscountLabel = new Label();
BestDiscountLabel.Text = " | | Book1 | ";
BestDiscountLabel.Text += "$" + price + " | ";
BestDiscountLabel.Text += "";
BestDiscountPlaceHolder.Controls.Add(BestDiscountLabel);
//put dynamic checkbox here
BestDiscountChkbox = new System.Web.UI.WebControls.CheckBox();;
BestDiscountChkbox.ID = "Book1:" + price.ToString();
BestDiscountPlaceHolder.Controls.Add(BestDiscountChkbox);
BestDiscountLabel = new Label();
BestDiscountLabel.Text = " | ";
BestDiscountPlaceHolder.Controls.Add(BestDiscountLabel);
BestDiscountPlaceHolder.Visible = true;
}
protected void AddToCartBtn_Clicked(object sender, ImageClickEventArgs e)
{
foreach (Control c in BestDiscountPlaceHolder.Controls)
{
if (c.GetType().ToString().Equals("System.Web.UI.WebControls.CheckBox"))
{
if (true == ((CheckBox) c).Checked)
{
Response.Write(((CheckBox) c).ID.ToString());
Response.Write("true");
}
else
{
Response.Write(((CheckBox) c).ID.ToString());
Response.Write("false");
}
}
}
}
}
-----------------------------------------------------------------------------------
GundamRX78
|
|
|
 |
|
 |
Everytime you click the image button,a postback occurs.This implies that,the page is going to be loaded once again.
Since,you are creating checkbox on every page load,the checkboxes you checked dies on occurrence of postback event ie.on being posted to server and you end up seeing new checkboxes each time WHICH WERE NEVER CHECKED ANYWAY.
So,you need VIEWSTATE to persist the values among postbacks.
Solution:
*Execute the code you have written in the page_load only once ie.during the first time the page is requested.
*Before you click the image button,save the state of the page in viewstate so that it can be retrieved during subsequent page loads.
Saswata Purkayastha
Satyam Computer Services.
|
|
|
|
 |
|
 |
but HOW do you save the control value in ViewState?!!!
|
|
|
|
 |
|
 |
I agree with you and i guess it would be a new property e.g. Textvalue that would be assigned to the viewstate but, i wonder if you can just drop few lines how it really should look like. I am confused about adding the new label's text value to the viewstate.
Thanks
|
|
|
|
 |
|
 |
i'm making polling project,but i've problem when how to find dynamic control that i've made.. i use this to create dynamic control: Protected WithEvents PilBox As System.Web.UI.WebControls.TextBox Protected WithEvents Table1 As System.Web.UI.WebControls.Table Protected WithEvents CreateOptionButton As System.Web.UI.WebControls.Button Protected WithEvents SaveButton As System.Web.UI.WebControls.Button Private Sub CreateOptionButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CreateOptionButton.Click Dim temp As Integer Dim i As Integer = PilBox.Text For temp = 1 To i Dim tb As New System.Web.UI.WebControls.TextBox tb.ID = "pil" & temp Dim mycell As New TableCell Dim c As New TableCell c.Controls.Add(New LiteralControl("Answers option " & temp & " : ")) mycell.Controls.Add(tb) Dim myrow As New TableRow myrow.Cells.Add(c) myrow.Cells.Add(mycell) Table1.Rows.Add(myrow) Next temp End Sub when i call it by click SaveButton : Private Sub SaveButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveButton.Click Dim temp As Integer Dim i As Integer = PilBox.Text For temp = 1 To i Dim myexisttb As TextBox myexisttb = Table1.FindControl("pil" & temp) 'save to database by calling myexisttb Next temp End Sub when i click SaveButton, dynamic control that i made before disappear.. and there's error : Object reference not set to an instance of an object. Anybody can help me?? Thanks before.. Merry Christmast and Happy New Year 2006 to you all....
ryuki
|
|
|
|
 |
|
 |
Hi!
Nice article!
I guess this is really useful for me but you didn't explain how can i obtain the data from those textboxes for update/insert on db.
Can anyone tell me how to do that?
What i'm doing is a dynamic list of fixtures with textboxes to fill the results (updating them - one by one - on the db).
Thanks a lot!
|
|
|
|
 |
|
 |
this may be too late for you, but i hope it may help concerning the data in the textboxes; you can make use of a class named HTTPContext, you should specifically define the following System.Web.HttpContext ctxRecieved = System.Web.HttpContext.Current; then you can loop through the elements in the page, your code may look something like this: for(int i=0;i<=ctxRecieved.Request.Form.Count;i++) { // get the key and value of the current element key = ctxRecieved.Request.Form.GetKey(i); val = ctxRecieved.Request.Form[key]; ... the key is a string value that represents the name of the element in the page the val is the text inside the textbox . Note: this procedure is only useful if called at the OnInit(..) method Ahmad Alsmair
|
|
|
|
 |
|
 |
Thank you very much!
Actually i've done it another way...but surelly this way will be useful in the folowing approaches to my project!
Thx a lot again,
Vitor Hugo Barros
|
|
|
|
 |
|
 |
Out of curiousity, how did you end up retrieving the values of your dynamically created controls after postback?
Thanks,
Ryan
|
|
|
|
 |
|
 |
hi,
i have a dynamically created survey page using the placeholder control.Once the user creates their survey i want it to be saved to a mysql database when they click the submit button.
im trying to loop thru the placeholder control and use findcontrol to find the actual text value of the placeholder so it can then be stored in a database.
it doesnt seem to be working but im not too sure how to use the findcontrol method anyway and theres no reference to it in any of the .net books i have
heres the snippet of code:
'Add TextBox Control
txtTextBox = New TextBox
txtTextBox.ID = "txtQuestion" & col.index
plhQuestionFields.Controls.Add(txtTextBox)
.
.
.
'add to mysql database
Sub btnSubmit_Click( s As Object, e As EventArgs)
dim ctrl as control
For Each ctrl In plhQuestionFields.Controls
ctrl = plhQuestionFields.FindControl("Qtext")
Cmd = New OdbcCommand ("INSERT INTO Questions1 (Qtext) VALUES (?)",conn)
Cmd.Parameters.Add("@Qtext",odbctype.varchar,255).value =
plhQuestionFields.controls
Next
conn.open()
Cmd.ExecuteNonQuery()
Conn.Close()
End Sub
..
..
..
<asp:PlaceHolder Id="plhQuestionFields" Runat = "Server"/>
i was also wondering ive read articles about problems with dynamic controls being lost after postback..if im saving to database this wont affect me will it,cos the articles were a little too complex for me to understand fully
really appreciate any help on this,ive been stuck on it for days
|
|
|
|
 |
|
 |
Can somebody tell me why the sample in the article does't work with Labels.
Vitor Pinto.
|
|
|
|
 |
|
 |
I have the same problem and would really like to know if there is a solution to this...
Best
Marc
|
|
|
|
 |
|
 |
when you add a label danamically into a page (using some script) you don't actually add a label you just add a <span></span> tag that contains the text and this is not parsed into a label when posted back Ahmad Alsmair
|
|
|
|
 |
|
 |
Hi all,
In my application i'm dynamically creating linkbutton controls and assigning some text with them. But still when this logic is applied to retain value during postback - it doesnt hold the text disappears.
Can abybody test with and get back to me with a solution.
Thanks,
Regards,
Kannadasan
|
|
|
|
 |
|
 |
Can anyone point to a free treeview control in ASP.net which suppoerts chechboxes & radiobuttons if poss..
|
|
|
|
 |
 | Events  |  | loginbajada | 4:09 16 Oct '03 |
|
 |
How i can add a event to a dinamic control???????
|
|
|
|
 |