Command event not firing asp.net for dynamically created control - c#

I've got the following code that creates an image button dynamically on a li html tag. When I click the image button it does not fire the event. What am I doing wrong please?
Code that generates the control:
ImageButton cmdEdit = new ImageButton();
cmdEdit.ImageUrl = "~/Images/phone_book_edit.png";
cmdEdit.ID = "cmdEdit" + recordcount.ToString();
cmdEdit.Attributes["class"] = "liQuestionsLabel2";
cmdEdit.Width = 30;
cmdEdit.CommandName = "Edit";
cmdEdit.CommandArgument = (recordcount - 1).ToString();
cmdEdit.Command += new CommandEventHandler(EditQuestion_Command);
li.Controls.Add(cmdEdit);
Event code:
protected void EditQuestion_Command(object sender, CommandEventArgs e)
{
Response.Write("here");
}

Dynamically generated controls lose their state after they are rendered. For you to access them again once you postback, you will have to recreate them in the code-behind along with recreating the attached events as well.
Put the above code in your Page_Load but not inside the if(!IsPostback) so that it gets recreated and you can then access its event.
Other than that, the above code works fine for me when I recreated the same control in my page.

Related

Problems firing my event for dynamically link buttons in asp

I have problems with my dynamically link buttons in asp pages. I use them for making a custom paging for a grid view. The idea is that i want to display them 20 about 20. It is working for first 20. When i display them it's all right. Then i press next for displaying the next 20. When i press next, it displaying me, but if a press a button other than the initial 20, it is going me at the first 20.
My init page:
override protected void OnInit(EventArgs e)
{
base.OnInit(e);
if (this.Tag.Equals("Shareholder"))
{
InitComponents(false);
}
/// Must be done everytime the page loads.
InitializeList();
if (!IsPostBack)
InitializeUI();
}
Init link buttons
private void InitComponents(Boolean Prev)
{
PanelPager.Controls.Clear();
int nrInregistrari = Convert.ToInt32(DAActionar.CountActionari(11, LastBtnIndex));
if (Prev == true)
{
LinkButton lnkPrev = new LinkButton();
lnkPrev.Text = "Prev";
PanelPager.Controls.Add(lnkPrev);
}
int BtnDeAfisat = 0;
if (nrInregistrari > BTN_PER_SERIE * PAGE_SIZE)
{
BtnDeAfisat = BTN_PER_SERIE;
}
else
BtnDeAfisat = nrInregistrari / PAGE_SIZE + 1;
for (int index = 1; index <= BtnDeAfisat; index++)
{
int pageNo = index + LastBtnIndex;
LinkButton lnk = new LinkButton();
lnk.Click += new EventHandler(PageChange);
lnk.ID = "PageLink" + pageNo.ToString();
lnk.CommandName = "Page";
lnk.Text = " " + pageNo.ToString() + " ";
lnk.CommandArgument = index.ToString();
PanelPager.Controls.Add(lnk);
}
LinkButton lnkNext = new LinkButton();
lnkNext.Click += new EventHandler(NextPage);
lnkNext.Text = "Next";
PanelPager.Controls.Add(lnkNext);
LastBtnIndex += BtnDeAfisat;
}
event for next buttons
private void NextPage(object sender, EventArgs e)
{
InitComponents(true);
}
PageChange:
public void PageChange(object sender, EventArgs e)
{
int pageIndex = int.Parse((sender as LinkButton).CommandArgument) + 1;
object dataSource = GetDataSource(OwnerId, null, pageIndex);
PushData(dataSource);
}
In ASP.NET only the controls which are added as part of Page_Load will have their events attached and will be executed. Also in when a server side event is executed the page posts itself back and during that the page_load executes first and then the event handler code gets executed.
So your first set of button events executed coz they were attached to event as part of page_load. Now during event of those button you are calling InitComponents method. So as I explained during the event page_load happens first which calls InitComponents method, which adds button to panel but InitComponents method executes again as part of event handler code which removes controls from Panel and re-creates them and add them again to the Panel.
Now since controls created during 2nd execution of InitComponents method are not no part of page_load flow events attached to them are not firing when you click on them. It just posts back the page which executed InitComponents again and which creates new controls in the panel and they will have their events working fine because they are created as part of page_load flow.
Pardon me if it confuses you.
Now the solution to this would be to use a control which can create many buttons automatically for you based on the number of items and also fires events all the times.
I do not have anything working right now for you. I found this article with working sample code which you can consider as an example and implement in your work.
http://www.aspsnippets.com/Articles/Implement-Paging-in-DataList-control-in-ASPNet.aspx
The example explains how to display page numbers and also how to bind your data based on the selected page number.

Dynamically created image button click event is not fired

On dynamically created table based on some condition i've added imagebutton dynamically. parallelly i want to add event for this image button click but the click event is not getting fired. here is my code snippet.
private void createTable()
{
TableRow tableRow = new TableRow();
TableCell ImageCell = new TableCell();
ImageButton imgBtndeleteAttr = new ImageButton();
imgBtndeleteAttr.ID = "imgbtn_" + i.ToString() + j.ToString();
imgBtndeleteAttr.CssClass = "deleteDynamic";
imgBtndeleteAttr.OnClientClick = "javascript:return confirm('Do you want to delete this Attribute?');";
imgBtndeleteAttr.Click += new System.Web.UI.ImageClickEventHandler(imgBtndeleteAttr_Click);
ImageCell.Controls.Add(imgBtndeleteAttr);
tableRow.Cells.Add(ImageCell);
}
and here is the event
protected void imgBtndeleteAttr_Click(object sender, ImageClickEventArgs e)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "lnk",
"<script type = 'text/javascript'>alert('Image button Clicked');</script>");
}
Its a bad idea to use dynamic controls in asp. The controls have to be recreated on postback. So if you create a button dynamically and click it, postback happens and event is triggered but due to postback the button which triggered the event is destroyed and the raised event is discarded.

Postback from Dynamic Content

I am dynamically building some HTML content on a WebForms page, using HtmlGenericControl().
HtmlGenericControl p = new HtmlGenericControl("p");
// ...
ListItems.Controls.Add(p);
But now I need to add a button to the paragraph created above, and the button needs to do a postback when clicked.
Must I completely rework this code to load child controls, which can contain real server-side buttons? Or is there a way to inject buttons capable of some type of postback?
Here's a test method and test EventHandler that, if called, will add a button control with a server-side Click event to ListItems. The commented-out code will change the markup of the ListItems object if InnerHtml is available but I rethought that approach and assumed the existence of a textbox on the page that would show the results of the click event firing. There are a number of concerns that you'll want to handle if you need those child controls to be present from one postback to another, though- for instance, if Test() isn't called every time the page loads that button won't be created and there will be no way to call its EventHandler unless other controls also call it.
public void Test()
{
System.Web.UI.HtmlControls.HtmlGenericControl p = new System.Web.UI.HtmlControls.HtmlGenericControl("p");
p.InnerHtml = #"<strong>Test</strong>";
// ...
ListItems.Controls.Add(p);
Button b = new Button();
b.ID = "cmdTest";
b.Text = "Test";
b.Click += new EventHandler(test_Click);
p.Controls.Add(b);
}
protected void test_Click(object sender, EventArgs e)
{
// ListItems.InnerHtml = "Test button clicked";
txtTestResults.Text = "Test button clicked at " + DateTime.Now.ToShortTimeString();
}

Dynamically created content is updating "a step behind" on button click

So I am creating a simple question/answer format and having an issue when submitting an answer. I dynamically create divs/buttons/textboxs from the database via a "RenderQuestions()" function. This creates a list of questions and answer textbox/buttons. When attempting to answer a question, I type my answer click submit and nothing happens. I do it again and it shows my first answer. It's a "step behind".. If I refresh it then shows all answers as it should. I've been struggling with this all night. Here's some code:
-----My page load----- (Relevant parts)
protected void Page_Load(object sender, EventArgs e)
{
//If authenticated hide login & show welcome bloc
if (User.Identity.IsAuthenticated)
{
//Show question & render
questionsBloc.Visible = true;
//if(Page.IsPostBack)
RenderQuestions();
}
-----RenderQuestions() function---- (The relevant parts)
//Initialize & get answers
List<Answer> answers = new List<Answer>();
answers = um.GetAnswers(q.QuestionID);
//Initialize html render
HtmlGenericControl questionDiv = new HtmlGenericControl("div");
TextBox txtAnswer = new TextBox();
Button btnAnswer = new Button();
//Set Answer Button
btnAnswer.Text = "Answer";
btnAnswer.Click += new EventHandler(btnAnswer_Click);
//Set ID's
btnAnswer.ID = "btnAnswer" + q.QuestionID.ToString();
questionDiv.ID = "questionDiv" + q.QuestionID.ToString();
//Set classes
questionDiv.Attributes.Add("class", "questionBloc");
btnAnswer.CausesValidation = false;
btnAnswer.EnableViewState = false;
//btnAnswer.UseSubmitBehavior = true;
//Fill inner text with question
questionDiv.InnerText = q.QuestionContent; //Insert question..
//actionDiv.InnerText = "Like/Dislike/Comment/Flag"; //Insert answer..
//Add answer textbox and button to action div
actionDiv.Controls.Add(btnAnswer);
//Add question div to qaDiv
qaDiv.Controls.Add(questionDiv);
//Add action div to qaDiv
qaDiv.Controls.Add(actionDiv);
//Add all controls to feedbloc
feedBloc.Controls.Add(qaDiv);
-----My btnAnswer event handler -----
private void btnAnswer_Click(object sender, EventArgs e)
{
UserManager um = new UserManager();
um.PostAnswer("My first answer!");
//RenderGlobalFeed();
}
That's every reference to my button.. Should I be initializing the btn click event in my page_init? Any help is much appreciated.
Thanks guys
Set AutoPostBack=true on btnAnswer. It's not triggering the server to act on the button click.
If you want to get event btnAnswer_Click triggered , then you must render the same Content and assign the eventHandler in every pageload(ie; the page load after the client button click must render the button again and EventHandler must be assigned).
Asp.net won't trigger the event if it doesn't find the controls in the pageload. Remember, after clicking a button, the page load event triggers first and then only the Click_event will be triggered.
The RenderQuestions() must be called in the btnAnswer_Click Event too. This will avoid the a step back problem.
In this scenario I would recommend you to learn about ajax (using jQuery library) requests in asp.net (using WebMethods or webservices) to avoid these postbacks.

tab container - event is not firing

i am creating a tab container at runtime and make 1 of the column member as the tab header
once user click on the tab i want to fire the event ActiveTabChanged.. if autopostback=true the entire tab container will gone but it got commend inside the event. if autopostback=false it can't go in the event and nothing happen at the layout.. hence i change the concept of my code..what i want is when user click on tab.. event are fire > everything remain same > next asp.net function will be call from the event. below are my coding
Remark- TabC is the tab container
<script type="text/javascript">
function ActiveTabChanged(sender, e) {
var Current_Tab = $get('<%#TabC.ClientID%>');
Current_Tab.innerHTML = sender.get_activeTab().get_headerText();
__doPostBack('TabC', sender.get_activeTab().get_headerText());
//Highlight(TabC);
}
</script>
in the body
<asp:TabContainer ID="TabC"
runat="server"
OnClientActiveTabChanged="ActiveTabChanged"
OnActiveTabChanged="ActiveTabChangedServer"
ActiveTabIndex="0"
/>
at Page Load
UpdatePanel oUpdatePanel = new UpdatePanel();
AsyncPostBackTrigger trigger = new AsyncPostBackTrigger();
protected void Page_Load(object sender, EventArgs e)
{
trigger.ControlID = "TabC";
trigger.EventName = "ActiveTabChanged";
oUpdatePanel.Triggers.Add(trigger);
Page.Header.DataBind();
ScriptManager.RegisterAsyncPostBackControl(TabC);
if (!Page.IsPostBack)
{
//runtime generate tab and gridview
Bind_Category_with_Tab();
}
}
error i get
output
the main problem is.. when i fire any event of the component in the page every things will disappear.. if the event can be trigger (AutoPostBack="true")
what mistake i have been done here? please to give a help here.. thanks advance

Categories