I Add Control Dynamiclly but; easc Postback event my controls are gone. I Can not see again my controls.
So How can I add control ?
Because you must recreate your controls on every postback,
see this article
Add the controls in the Page's Init event and they will be preserved in viewstate when posting back. Make sure they have a unique ID.
See this link...
ASP.NET Add Control on postback
A very trivial example..
public partial class MyPage : Page
{
TextBox tb;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
tb = new TextBox();
tb.ID = "testtb";
Page.Form.Controls.Add(tb);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
//tb.Text will have whatever text the user entered upon postback
}
}
You should always assign a unique ID to the UserControl in its ID property after control is loaded. And you should always recreate UserControl on postback.
To preserve posback data (i.e. TextBox'es) you must load UserControl in overriden LoadViewState method after calling base.LoadViewState - before postback data are handled.
Add controls in runtime and save on postback:
int NumberOfControls = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["b1"] = 0;
}
else
{
if ((int)ViewState["b1"] > 0)
{
CreateBtn();
}
}
}
protected void btn1_Click(object sender, EventArgs e)
{
NumberOfControls = (int)ViewState["b1"];
Button b1 = new Button();
// b1.Attributes.Add("onclick", "x()");
b1.Text = "test2";
b1.ID = "b1_" + ++NumberOfControls;
b1.Click +=new System.EventHandler(btn11);
Panel1.Controls.Add(b1);
ViewState["b1"] = NumberOfControls;
}
protected void CreateBtn()
{
for (int i = 0; i < (int)ViewState["b1"];i++)
{
Button b1 = new Button();
// b1.Attributes.Add("onclick", "x()");
b1.Text = "test2";
b1.ID = "b1_" + i;
b1.Click += new System.EventHandler(btn11);
Panel1.Controls.Add(b1);
}
}
protected void btn11(object sender, System.EventArgs e)
{
Response.Redirect("AboutUs.aspx");
}
Related
I try to make a simple application in which I have a dropdown list with tems - numbers from 1 to 4.
Depending on the number the user choose - I create dynamically this number of checkboxes with binded checkedchanged event. So when the user checks some of the checkboxes so checkedchanged event is raised and I store the text of the checked checkbox in session and then when I click a button I want to see the text only from the checked checkboxes.
But it seems that the checkedchanged event handler is never triggered.
Thank you in advance
public partial class proba : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
dd1.Items.Add("1");
dd1.Items.Add("2");
dd1.Items.Add("3");
dd1.Items.Add("4");
}
protected void dd1_SelectedIndexChanged1(object sender, EventArgs e)
{
int numTourists = Convert.ToInt32(dd1.SelectedItem.Text);
for (int i = 0; i < numTourists; i++)
{
CheckBox chk = new CheckBox();
chk.ID = "chk" + i;
chk.Text = "box" + i;
chk.CheckedChanged += new EventHandler(checkChanged);
Page.FindControl("form1").Controls.Add(chk);
}
}
protected void checkChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
lblpr.Text += chk.Text;
Session["chk"] = chk.Text;
}
protected void btnpr_Click(object sender, EventArgs e)
{
lblpr.Text = "length" + ((String [] )Session["chk"]).Length;
for (int k = 0; k < ((String[] )Session["chk"]).Length; k++)
{
lblpr.Text += ((String [])Session["chk"])[k];
}
}
}
You need to set AutoPostBack property of checkbox as true in order to post back when check changed
chk.AutoPostBack = true;
And read this also
adding an event handler to a dynamically created checkbox (aspx, c#)
change page load, you don't need to add items again and again in each page post back
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//Load dd1
}
}
But you need to add dynamic controls on each page post back, better do it on OnInit as above answer in the link suggested
since you are creating checkbox dynamically, it get lost when there is the post back.
So you need to add those again before pageload event so that during page load event they are visible to .net and hence .net can fire their corresponding event.
B4 you dive into dynamic control it is good idea to get the basic which can be found at https://web.archive.org/web/20210330142645/http://www.4guysfromrolla.com/articles/092904-1.aspx
I am creating a button dynamically and place it in a placeholder as below
<asp:Button ID="generateTableSchema" runat="server" Text="Generate Table" OnClick="generate_Click" />
protected void generate_Click(object sender, EventArgs e)
{
Button button = new Button();
button.Text = "Generate Table";
button.ID = "generateTable";
button.OnClick = hello();
PlaceHolder1.Controls.Add(button);
}
but onclick event is not firing.
this is the error i am getting
System.Web.UI.WebControls.Button.OnClick(System.EventArgs)' is inaccessible due to its protection level
hello is as below...
public void hello()
{
Label1.Text = "heellllllllllo";
}
What's wrong here????
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
else
{
button.Click += ButtonClick;
}
}
#Daren u mean like this...
Because you are adding the button programmatic ally you have to add the event handler.
So this would work..
EDIT
Wrapped the button INSIDE Page_Load
protected void Page_Load(object sender, EventArgs e)
{
Button button = new Button();
button.Text = "Generate Table";
button.ID = "generateTable";
button.Click += hello; /// THIS is the handler
PlaceHolder1.Controls.Add(button);
}
ButtonClick would be the name of your method.
protected void hello(Object sender, EventArgs e)
{
// ...
}
Also, as you're generating this at runtime you need to makesure this gets called on postbacks too.
The OnClick is a protected method. You should use the event Click.
button.Click += new EventHandler(Click);
public void hello(object sender, EventArgs e)
{
Label1.Text = "heellllllllllo";
}
By the way, make sure you create and add the control in every postback, otherwise the event won't work.
Change button.OnClick = hello(); to:
button.Click += new EventHandler(hello);
And change the definition for hello() to:
protected void hello(object sender, EventArgs e)
{
Label1.Text = "heeellllllo";
}
The event is called Click. You need to add the event handler with the correct signature:
button.Click += new EventHandler(hello);
and the signature is:
protected void hello(Object sender, EventArgs e)
{
// ...
}
How to: Add an Event Handler Using Code
Note that you need to recreate dynamical controls on every postback.
You assigning the result of executing hello().
Try assigning:
button.OnClick = hello;
-- edit--
apparantly, that does not clarify your error.
Add the handler to the event handler in stead:
button.Click += hello;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
else if(Page.IsPostBack && Label11.Text=="yes")
{
Button button = new Button();
button.Text = "Generate Table";
button.ID = "generateTable";
button.Click += ButtonClick;
PlaceHolder1.Controls.Add(button);
}
}
setting
Label11.Text = "yes";
in generate_click.
protected void ButtonClick(object sender, EventArgs e)
{
Label1.Text = "heeellllllo";
}
So I have a listbox on my page and some textfields. Through the textfields I can add an item to my listbox (click the button, it adds it to a private List<string> which is then set as a ViewState and the list is databound again).
My listbox is also in an updatepanel which gets triggered on the button's Click event.
Problem: My Viewstate remains null on a postback so it gets reset each time.
Some code:
private List<IngredientData> _ingredientsList;
protected void Page_Load(object sender, EventArgs e)
{
// prepare ingredient lists
_ingredientsList = new List<IngredientData>();
if (Page.IsPostBack)
{
if (ViewState["IngredientsList"] != null)
{
_ingredientsList = (List<IngredientData>) ViewState["IngredientsList"];
}
}
lstIngredients.DataSource = _ingredientsList;
lstIngredients.DataTextField = "Text";
lstIngredients.DataValueField = "Name";
lstIngredients.DataBind();
}
protected void btnAddIngredient_Click(object sender, EventArgs e)
{
_ingredientsList.Add(new IngredientData { Name = txtIngredientName.Text, Quantity = txtUnitQuantity.Text, Unit = lstUnits.SelectedValue });
ViewState["IngredienstList"] = _ingredientsList;
lstIngredients.DataSource = _ingredientsList;
lstIngredients.DataBind();
}
Any idea how I can fix this? Am I doing something wrong?
btnAddIngredient_Click is adding to "IngredienstList" not "IngredientsList" (note the spelling).
You can avoid this kind of typo by using a constant:
private const string IngredientsListViewStateKey = "IngredientsList";
then referring to it like this:
ViewState[IngredientsListViewStateKey] = _ingredientsList;
i careate button control and place in panel but not working?
protected void Button1_Click(object sender, EventArgs e)
{
Button btn = new Button();
btn.Text = "Test button";
Panel1.Controls.Add(btn);
btn.Click += new EventHandler(btn_Click);
}
void btn_Click(object sender, EventArgs e)
{
Response.Write("<script>alert('test')</script>");
}
When you dynamically add controls to your page, you have to re-add them on any subsequent request (postback). The button you added in Button1_OnClick will not automatically be recreated in a subsequent request (e.g. in a postback).
There a lot's of similar questions about this topic, where you can find details. For examples, use the following search:
https://stackoverflow.com/search?q=dynamic+control+event+[asp.net]
Make sure you assign an ID to the button, and make sure it's the same everytime you create it.
Create the control in the CreateChildControls overload, adding it once in response to another event isn't going to be enough to keep it on the page.
You're best bet is going to be tracking the whether the button needs to be created or not:
bool CreateButton
{
get
{
if (ViewState["CreateButton"] == null)
return false;
return (bool)ViewState["CreateButton"];
}
set
{
ViewState["CreateButton"] = value;
}
}
override void public CreateChildControls ()
{
panel1.Controls.Clear ();
if (CreateButton)
{
Button btn = new Button();
btn.Text = "Test button";
btn.ID = "CreatedButton"; // Note the ID here...
Panel1.Controls.Add(btn);
btn.Click += new EventHandler(btn_Click);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
CreateButton = true;
EnsureChildControls ();
}
void btn_Click(object sender, EventArgs e)
{
Response.Write("<script>alert('test')</script>");
}
Something like that should work for you...
I have a datagrid (Asp.Net) with dynamically generated checkbox column..I am not able to generate the checkedChanged event for the checkbox..
Here is my code:
public class ItemTemplate : ITemplate
{
//Instantiates the checkbox
void ITemplate.InstantiateIn(Control container)
{
CheckBox box = new CheckBox();
box.CheckedChanged += new EventHandler(this.OnCheckChanged);
box.AutoPostBack = true;
box.EnableViewState = true;
box.Text = text;
box.ID = id;
container.Controls.Add(box);
}
public event EventHandler CheckedChanged;
private void OnCheckChanged(object sender, EventArgs e)
{
if (CheckedChanged != null)
{
CheckedChanged(sender, e);
}
}
}
and Here is the event
private void OnCheckChanged(object sender, EventArgs e)
{
}
Thanks In advance
When do you add your custom column? If it is on load, then it is too late. Load it on init. I.e. following works with your code:
protected void Page_Init(object sender, EventArgs e)
{
ItemTemplate myTemplate = new ItemTemplate();
myTemplate.CheckedChanged += new EventHandler(myTemplate_CheckedChanged);
TemplateField col = new TemplateField();
col.ItemTemplate = myTemplate;
col.ItemStyle.Wrap = false;
grid.Columns.Add(col);
}
If your checkbox ID's are not being set the same way on every postback, then they can never be connected to the event handlers when it comes time to process the events. Where is your field "id" coming from?