Dynamically added buttons wont work from the first click - c#

i know there is a lot of questions similar to mine but none of them solved my problem.
The Idea:
i have two pages the first one is a login page and the other one is to show the logged in person attendance, in the attendance page i have two tabs one for the employee itself and the other one is to dynamically show the names of the employees under him, the second tab is presented as buttons that contain the employees name, and when you click it, it shows that person attendance.
The Problem:
when i click on the button it refresh the page without doing anything then when i click it again it works and calls the method i needed, so my question is why it doesn't work from the first click ?
Solution Attempt:
i created the buttons in code behind this way :
var button = new Button
{
ID = "Button " + a,
CommandArgument = myEmp[a].ToString(), //id of employee
Text = GetName(myEmp[a]), // name of employee
CausesValidation = false
};
button.Command += GetINAndOutManagers; //method on click
var cell = new HtmlTableCell();
var row = new HtmlTableRow();
cell.Controls.Add(button);
row.Cells.Add(cell);
myTable.Rows.Add(row); // just for organization i put them in a table
and in my html page :
<table id="myTable" runat="server" class="table table-bordered"></table>
as a place holder.
1- i have JavaScript and jquery in my page but even when i remove them it doesn't work.
2- i tried using html buttons instead in code behind put still don't work.
3- i tried putting it in page init and page preinit but no result.
the only time it worked when i put the buttons in the main page not the content page i don't know why, and i noticed when i click the button for the first time it doesn't consider it as a post back.
any ideas ?
EDIT
so to make it easier i deleted everything in my page load method
and in my page init method i have this code only.
protected void Page_Init(object sender, EventArgs e)
{
Button btn = new Button();
pnlInfo.Controls.Add(btn);
btn.ID = "Button" + 1.ToString();
btn.Text = "Test button" + 1.ToString();
btn.Click += new EventHandler(btnSubmit_click);
}
and the method on click is like this:
private void btnSubmit_click(object sender, EventArgs e)
{
System.Diagnostics.Debug.Write("**************in*****************");
}
so i only login and then it will redirect me to the second page which contains one button only created as you see in my page init method, no tabs no nothing
and in my html is this
<asp:Panel ID="pnlInfo" runat="server">
</asp:Panel>
with some css and divs that's all, and it's still won't work from the first click !

Oh Gosh, i found my solution
in my login page i used this code to transfer to my second page:
Server.Transfer("About.aspx", true);
so my buttons did not work, but when i change the code to this:
Response.Redirect("About.aspx");
everything worked !
well i'm an asp.net beginner so i don't know why that solved
my problem. but thanks everyone, hope this help someone else too.

Related

EnableViewState for html tag

I am quite new and I will like to ask a question. Please see the html and codebehind.
HTML
<ul id="menu" runat="server" EnableViewState="True"></ul>
CodeBehind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var liItem = new HtmlGenericControl("li");
var aItem = new HtmlGenericControl("a");
liItem.Attributes.Add("class", "test");
aItem.Attributes.Add("href", "#");
aItem.InnerText = "please work";
liItem.Controls.Add(aItem);
menu.Controls.Add(liItem);
}
}
Once postback, the UL data is lost though I have enabled the viewstate. I remember it works last time but now it is not. Anybody can advise? Thanks a lot
This happens because you are dynamically adding data via your first load (!IsPostback), and thereafter (when Page_Load runs again) the data is being lost. You have to keep in mind that EnableViewState is a ASP.NET specific property, So it will only work on server controls inheriting from System.Web.UI.Control
The only way you can achieve this is by either creating your html tags on each and every page load (i.e remove your !IsPostBack check)
or adding a ASP.NET control to the page which supports ViewState (Gridview, ListView, Label, Button etc).

ASP.NET : my html element repeated after my postback finish

i have an asp web page and my page contains to RadCombobox. for first drop down i set item_requested method (when the user click on it and select the theater name.it has a post back and after post back the second drop down fill with sans numbers ).
my problem is here:
after page post back the second field set duplicate in my page. in these pictures you can see that.
Before post back:
the second image :(After postback the second fielset repeated)
Note:
all of my controls in update panel. after i remove update panel from my page i doesn't happen again.Do you know the reason ? :[
You probably have some logic where you are adding this component. Try to check IsPostBack before adding the component to the page. Just like that:
if (!IsPostBack)
{
//dynamically add component
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
// ASPX C#
}
}
ASP
................... IM NOT GOOD AT ASP

How to update the first page from the second redirected page?

I have two pages :
page1.aspx
page2.aspx
The first one has a GridView which open the second page .
I want to open the second page and when submit it updates the Gridview in the first page to reflect the changes .
protected void gv_inbox_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "sign")
{
Session["main_code"] = int.Parse(((HiddenField)gv_inbox.Rows[index].Cells[1].FindControl("HDN_MainCode")).Value);
Session["year"] = int.Parse(((HiddenField)gv_inbox.Rows[index].Cells[1].FindControl("HDN_Year")).Value);
Session["values_key"] = gv_inbox.DataKeys[index].Value.ToString();
String js = "window.open('page2.aspx', '_blank');";
ClientScript.RegisterClientScriptBlock(this.GetType(), "Open Signature.aspx", js, true);
}
}
I want when click on the button [Confirm] in the page2.aspx to update the first page .
and close the second page
I think you have some form in the second page on submission of which you want to show newly submitted data into the gridview? If this is the case, on submit of first form, you should just reload the page1.aspx.
SO to do this: simply use js trick "self.parent.location.href=self.parent.location.href;" on click of button [Confirm].
The best thing to do is to put a button on page 2 that redirects again to page 1. Another option is to have a timer that after a few second it will go back to page 1.

FindControl in MasterPage, first click generates empty string

My web site uses a master page, where I've placed two controls, a TextBox and an ImageButton, they are intended to be viewed and accessible on all content sites. Here's the aspx code in Site.Master:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:ImageButton ID="ImageBtn" runat="server" ImageUrl="~/Image.png"
PostBackUrl="~/Result.aspx"></asp:ImageButton>
Clicking the button should redirect the visitor to Result.aspx, which it does.
Result.aspx.cs has the following in the Page_Load event:
protected void Page_Load(object sender, EventArgs e)
{
TextBox txbx = this.Master.FindControl("TextBox1") as TextBox;
if (txbx != null)
{
Label1.Text = "Value: " + txbx.Text;
}
else
{
Label1.Text = "TextBox seems to be null";
}
}
The weird behavior appears when the image button is clicked the first time. The visitor gets this information from the page "Value: " (i.e an empty string ""), even though a value was entered in TextBox1. The subsequent clicks presents the value(s) correctly, e.g "Value: SomeText".
Why doesn't the value "come along" the first time?
Is there a better way to ensure that?
The visitor is redirected to Result.aspx AND
that the value is "registered" and can be handled in Result.aspx.cs AND
that a user will be redirected, if Result.aspx is entered without the use of the image buttons PostBackURL
I've tried IsPostBack but it seems to behave strangely when using a master page as previous page ...
Very thankful for an answer!
Sincerely,
Mr Kay
If you are using PostBackURL on your ImageButton on the master page and come from another page you must use:
PreviousPage.Master.FindControl("TextBox1") as TextBox;
If you are on the PostBackURL page and click your ImageButton, you need to use
Master.FinControl("TextBox1") as TextBox;
(PreviousPage would be null in this case)
you could use something like this:
var txbx = PreviousPage == null ?
Master.FindControl("TextBox1") as TextBox :
PreviousPage.Master.FindControl("TextBox1") as TextBox;
See: http://msdn.microsoft.com/en-us/library/system.web.ui.page.previouspage(v=vs.100).aspx
at the Remarks section.
Since you know your form is derived from the master... have you tried explicit type-casting to get at it??? such as
TextBox txbx = ((site.Master)this).Textbox1;
then do whatever you want from there... It's been a while since I've been into asp.net, but remember doing something similar in one of my older apps.

Nested usercontrol Linkbutton Onclick event not firing after postback - asp.net/C#

I'm using nested controls for a series of forms and having problem with the onclick event.
I'm just using textboxes and a manual code-behind insert rather than Gridview/Details view structure.
The scenario is that I have a car insurance form where users can add additional named drivers. At the top is a section where you add your own details (which is a seperate user control) and there is a section underneath where you can add up to 4 named drivers (which is also a seperate usercontrol). What I wanted to do was use my 'Add Driver' linkbutton onclick event to add the details into the database, then clear the form fields so the user could then add another driver. This all works fine until you go to click the Add Driver button again and discover it doesn't work.
This is the Parent control that houses the Add Driver user control:
<h2>Add Permanent Driver</h2>
<asp:ValidationSummary ID="uxValidationSummary" runat="server" ShowSummary="true" ValidationGroup="ChangeDetails" />
<div class="clear"></div>
<h3>
Please enter your details below as they are on your insurance documents</h3>
<uc1:UserDetails ID="uxUserDetails" runat="server" />
<uc2:AddDriver ID="uxAddDriver" EntryType="Permanent" runat="server" />
This is a cutdown version of the onclick event for the Add Driver submit button on the AddDriver control
protected void uxSubmit_Click(object sender, EventArgs e)
{
Page.Validate("AddDriver");
if (Page.IsValid)
{
DriverDAL.DriverTableAdapters.DriverTableAdapter taDriver = new DriverDAL.DriverTableAdapters.DriverTableAdapter();
taDriver.DriverInsert(StartDate, EndDate, Title,
FirstName, Surname, DateOfBirth, Gender);
uxDriverList.DataBind();
uxDate.Text = string.Empty;
uxEndDate.Text = string.Empty;
uxTitle.SelectedIndex = 0;
uxFirstName.Text = string.Empty;
uxSurname.Text = string.Empty;
uxDateOfBirth.Text = string.Empty;
uxGender.SelectedIndex = 0;
}
}
Is there anything I can do to reactivate this linkbutton after the first OnClick (or remove it and recreate it) so I can add multiple drivers? I tried to databind the button after the submit, but as expected, that had no effect, but that is the kind of thing I'm looking for. I can't redirect the page, because as mentioned earlier in the post, it is using nested controls and I arrive at this form by using the SelectedIndexChanged event of a DropDownList.
Any ideas appreciated - thanks. Let me know if more info is required.
It sounds like you might have some validation that's preventing the button from doing a postback. Try setting CausesValidation="false" and see if that makes a difference.
If validation is causing the problem, I would either separate the validation into groups and assign the button to a specific group, or toggle the enabled state of the validators based on some condition, for example:
RequiredFieldValidator1.Enabled = Panel1.Visible;

Categories