I am doing custom paging for a datalist.Below method gets the required page numbers.
My problem is the click event is not being fired during debug.
Can anyone tel where the problem is.
private void BindPageNumbers(int TotalRecords)
{
int counter = 0;
for(int i=0;i<TotalRecords;i=i+5)
{
counter=counter+1;
LinkButton lnk = new LinkButton();
lnk.Click += new EventHandler(lbl_click);
lnk.ID = "lnkPage" + (counter).ToString();
lnk.Text = (counter).ToString();
pages.Controls.Add(lnk);
Label spacer = new Label();
spacer.Text = " ";
pages.Controls.Add(spacer);
}
}
void lbl_click(object sender, EventArgs e)
{
LinkButton lnk = sender as LinkButton;
int Currentpage = int.Parse(lnk.Text);
ListDataBinding_paging(2, this.Days, (Currentpage-1)*5, 5);
}
Here "ListDataBinding_paging" is the method from where the datalist is being filled.
You are creating your page link buttons dynamically. So they need to be re-created in every post-back early in the life-cycle. I suspect that BindPageNumbers is getting called after the post event data is processed and hence the click event does not get generated.
I suggest you to invoke BindPageNumbers in page_load for creating your buttons early in the life cycle. You can store the total records count in the view-state. If page_load doesn't help then try LoadViewState override - put the code after call to base implementation - something like
protected override void LoadViewState(Object savedState)
{
base.LoadViewState(savedState);
BindPageNumbers((int)ViewState["TotalRecords"]);
}
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
am creating some TextBoxes by backend on a text change event, Like this :
protected void txtHowMany_TextChanged(object sender, EventArgs e)
{
int totalSections = Convert.ToInt32(txtHowMany.Text.Trim());
for (int i = 1; i <= totalSections; i++)
{
TextBox tbx = new TextBox();
tbx.Text = "";
tbx.ID = "section" + i;
tbx.Style.Add("width", "90%");
tdSectionsAdd.Controls.Add(tbx);
}
trSectionsName.Visible = true;
}
The auto post back is true for txtHowMany, so when I enter a number, it generates the textboxes and add it to table division
Now the problem is, I am trying to get text from generated textboxes like this :
protected void btnSave_click(object sender, EventArgs e)
{
int numbersOfSectionsToSave = 1;
int sectionsToSave =Convert.ToInt32(txtHowMany.Text.Trim());
for (int i = 1; i < sectionsToSave; i++)
{
Sections section = new Sections();
section.CourseId = result;
section.OrganizationId = course.OrganizationId;
foreach (Control c in tdSectionsAdd.Controls)
{
if (c.GetType() == typeof(TextBox))
{
TextBox txtBox = (TextBox)c;
string id = "section" + i;
if (txtBox.ID == id)
{
section.Name = txtBox.Text.Trim();
}
}
}
string name = Request.Form["section1"];
section.CreatedBy = "Admin";
section.CreationDate = DateTime.Now;
section.ModifiedBy = "Admin";
section.ModificationDate = DateTime.Now;
numbersOfSectionsToSave += section.SaveSection();
}
But its showing 0 count for the controls in tdSectionsAdd , The controls are added before I am trying to access them, but still it shows no controls in td.
Please help, How can I get these textboxes?
Thanks!
You need to add them in each postback. Store the totalSections variable in ViewState so you can add them i page load also:
protected void AddTextBoxes()
{
int totalSections;
if (int.TryParse(Convert.ToString(ViewState["TotalSections"]), out totalSections)
{
for (int i = 1; i <= totalSections; i++)
{
TextBox tbx = new TextBox();
tbx.Text = "";
tbx.ID = "section" + i;
tbx.Style.Add("width", "90%");
tdSectionsAdd.Controls.Add(tbx);
}
trSectionsName.Visible = true;
}
}
protected void txtHowMany_TextChanged(object sender, EventArgs e)
{
ViewState["TotalSections"] = Convert.ToInt32(txtHowMany.Text.Trim());
tdSectionsAdd.Controls.Clear();
AddTextBoxes();
}
protected void Page_Load(object sender, EventArgs e)
{
AddTextBoxes();
}
Dynamic Created controls "Disappear" on postback, if they are not "recreated" in the Page_Init of that page.
Only if they are created in the page_init will the page's viewstate get updated with their information.
Long Explantion:
When we perform a postback (or partial postback) we want to be able to access those controls (or at least the values the user put into them).
We know that the data is in the viewstate, but ASP.NET doesn’t really know which control a ViewState item belongs to. It only knows to match a viewstate item and a control through the same index (e.g. Matches item n in the viewstate tree to item n in the control tree). Therefore in order to get the dynamic controls' data, we need to re-create the controls each time the page is postbacked.
BUT in order for this to work, we need to re-create the controls in the Page_Init function NOT in the Page_Load.
Why? Because when the ViewState is created it needs all the controls to already exist.
This is taken from MSDN, as you can see the viewstate is loaded AFTER the init but before the page load.
TL;DR Call the function that creates the dynamic controls in the page_init and you should be able to see all the values the user entered when the page postbacks
A few links on this issue:
http://forums.asp.net/t/1186195.aspx/1
ASP.NET - Dynamic controls created in Page_Pre_init() or Page_Init() or Page_Load()
Option 2:
I should note: If the controls all had unique Ids and you're not interested in re-creating them again every postback - you could always look for them in the Request Object.
The Request.Form is a NameValueCollection that holds the values of all the controls that were part of the form, just search it for whatever you're looking for
I have a page to do a heirarchical search, it starts with a dropdownlist and based on the value selected in the dropdown it will query the database and show the childs in another dropdown list and this continues as long as it hits the leaf... so I've first dropdown added dynamically and it has the event handler on SelectedIndexChanged, when I change the selected value, it triggers the postback but however not calling event handler method.. Not sure what i'm doing wrong here.. or is it a bug??
Using a session variable to keep track the created controls
private List<DynamicControlProperties> PersistedControls
{
get
{
if (_persistedControls == null)
{
if (Session[PersistedControlsKey] == null)
{
Session[PersistedControlsKey] = new List<DynamicControlProperties>();
}
_persistedControls = Session[PersistedControlsKey] as List<DynamicControlProperties>;
}
return _persistedControls;
}
}
And in Page Init, recreating the dynamically generated controls
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
// regenerate the persisted controls
foreach (var prop in PersistedControls)
{
CreateControl(prop);
}
}
In page load, created the very first dropdown
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// create the control
CreateControl(....)
// bind the data to the dropdown
}
}
In create control method, just creating a label and a dropdown wrap it inside a and adding it to place holder
private DropDownList CreateControl(DynamicControlProperties dynamiccntrlprop)
{
// create a new HTML row
HtmlGenericControlWithParentID tr = new HtmlGenericControlWithParentID("tr");
HtmlGenericControlWithParentID td1 = new HtmlGenericControlWithParentID("td");
HtmlGenericControlWithParentID td2 = new HtmlGenericControlWithParentID("td");
// make sure we set the id and parentid
tr.ID = string.Format("tr{0}", dynamiccntrlprop.ID);
tr.ParentID = dynamiccntrlprop.ParentID;
tr.EnableViewState = true;
// create a new label for dropdown
Label lbl = new Label() { ID = string.Format("lbl{0}", dynamiccntrlprop.DisplayName), Text = dynamiccntrlprop.DisplayName };
// create a new dropdown list
DropDownList ddl = new DropDownList()
{
ID = string.Format("ddl{0}", dynamiccntrlprop.DisplayName),
// set the postback
AutoPostBack = true,
EnableViewState = true
};
// subscribe for the select index changed event
ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
// add the controls to table row
td1.Controls.Add(lbl);
td2.Controls.Add(ddl);
tr.Controls.Add(td1);
tr.Controls.Add(td2);
// add the control to place holder
this.filtersPlaceHolder.Controls.Add(tr);
return ddl;
}
Here is the index changed handler,
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
}
Enabled the viewstate,autopostback blah blah blah... recreated the controls with same id in post back.. tried all the answers in google.. but NO luck.. It does trigger the postback when i changed the index but not calling the event handler method..
Any ideas, please???
Many Thanks,
K
You have to make sure that The CreateControl method is called on each and every page postback. This needs to happen to ensure that the dynamic control's event handler is hooked up after the postback.
protected void Page_Load(object sender, EventArgs e)
{
// you shouldn't wrap the call to CreateControl in this 'if' statement
//if (!Page.IsPostBack)
//{
// create the control
CreateControl(....)
// bind the data to the dropdown
//}
}
once you do this, the selected index changed event will fire.
Maybe It is beacuse new value of the dropdownlist don't be loaded.
protected override void LoadViewState(object savedState)
{
// regenerate the persisted controls
foreach (var prop in PersistedControls)
{
CreateControl(prop);
}
base.LoadViewState(savedState);
}
I have a code snippet like below and I want to add imagebuttons into my asp:Panel during page load. But the events are firing already when I run the page. I want it to be fired when it is clicked.
Thanks in advance for all helps
protected void Page_Load(object sender, EventArgs e)
{...
foreach (Gift g in bonusGifts)
{
ImageButton ib = new ImageButton();
ib.ImageUrl = g.GiftBanner;
ib.ID = g.GiftID.ToString();
ib.Click += Purchase(g);
BonusGiftPanel.Controls.Add(ib);
}
}
private ImageClickEventHandler Purchase(Gift g)
{
_giftRep.Purchase(g, _userSession.CurrentUser);
lblGifts.Text = "You have purcased " + g.GiftName + " for " + g.BonusPoints;
return null;
}
Add controls in your Page_Init, not in your Page_Load. [1]
Furthermore, you are not doing this the way it should. Consider this code
//your collection of objects goes here. It might be something different than
//this, but basically a Dictionary<int, YourType> goes fine
public Dictionary<Int32, string> Ids
{
get { return (ViewState["ids"] ?? new Dictionary<Int32, string>()) as Dictionary<Int32, string>; }
set { ViewState["ids"] = new Dictionary<Int32, string>(); }
}
protected void Page_Init(object sender, EventArgs e)
{
//load the data using your DAO
Ids = new Dictionary<int, string>();
Ids.Add(1, "http://www.huddletogether.com/projects/lightbox2/images/image-2.jpg");
Ids.Add(2, "http://helios.gsfc.nasa.gov/image_euv_press.jpg");
foreach (var item in Ids)
{
ImageButton imb = new ImageButton()
{
ImageUrl = item.Value,
CommandArgument = item.Key.ToString(),
CommandName = "open"
};
imb.Click += new ImageClickEventHandler(imb_Click);
PH1.Controls.Add(imb);
}
}
void imb_Click(object sender, ImageClickEventArgs e)
{
Response.Write("You purchased " + Ids[int.Parse(((ImageButton)sender).CommandArgument)]);
}
[1] (CTRL+C/CTRL+V from some other question I answered last week):
Everything that has to be maintained between page cycles should be declared in Page_Init, not Page_Load.
All the initialization, like adding event handlers, and adding controls should be added during initialization, as the state is saved between page cycles. Handling with the content of controls and the viewstate, should be done in Load.
Check also http://msdn.microsoft.com/en-us/library/ms178472.aspx.
Init
Raised after all controls have been initialized and any skin
settings have been applied. Use this
event to read or initialize control
properties.
.
Load
The Page calls the OnLoad event method
on the Page, then recursively does the
same for each child control, which
does the same for each of its child
controls until the page and all
controls are loaded.
Use the OnLoad event method to set
properties in controls and establish
database connections.
You should add the controls in the Page Init event, as other have said.
Your image click event handler does not conform to the ImageButton Click event handler signature. That should look something like this:
private void ImageButton_Click(ByVal sender As Object, ByVal e As ImageClickEventArgs)
{
}
Note that you can't pass your "Gift" object directly to the ImageButton_Click. You will have to find another method of doing that.
You need to take a look at the Page Lifecycle - http://msdn.microsoft.com/en-us/library/ms178472.aspx
I'm creating a fileupload control on a linKbutton click event. First time it's creating the controls, but if I press the link button second time, it's not creating. What is the problem with that? The following is my code:
protected void LinkButton1_Click(object sender, EventArgs e)
{
newattach();
}
private void newattach()
{
int i;
for (i = 0; i < 2; i++)
{
count++;
FileUpload f1 = new FileUpload();
f1.ID = "fileupload" + count.ToString();
f1.Height = 34;
f1.Width = 212;
Panel1.Controls.Add(f1);
}
}
and count is a static variable. Please help.
When you create controls dynamically with ASP.NET you need to recreate the control every time you post back, generally you recreate the control on Page_Load. That is most likely the cause of your problem.