Having to click button twice to trigger postback in asp.net - c#

I have some validation code in my searchbutton click event and have been having problems with it having to be clicked twice to work.
Asp Code:
<asp:Button ID="SearchButton" runat="server" Text="Search" Width="148px" OnClick="SearchButton_Click" style="height: 35px" />
Code Behind
protected void SearchButton_Click(object sender, EventArgs e)
{
string title = TitleSearch.Text;
Regex rgx = new Regex("^[0-9A-Za-z ]+$");
if (title != "" && !rgx.IsMatch(title))
{
ErrorLabel.Text = "Special characters are not allowed";
}
else
{
SearchButton.PostBackUrl = "results.aspx";
}
}

does the textbox have postback ? becaus if you change the text in the textbox it will do postback when you leave the textbox.so if you click the button the postback of the textbox fires.
I would check the textbox with java
Add in you page load event "Change EditGroup to the TextBoxName you want to check"
EditGroup.Attributes.Add("onchange", "return SomeTextChanged();");
This will add an onchange event to the textbox and it will call the java function in your aspx page when you click the button
Then in your aspx page you add "Again change EditGroup to the name of the TextBox you want to check"
<script type="text/javascript">
function SomeTextChanged() {
var Entered = document.getElementById('<%= EditGroup.ClientID %>');
if (Entered.value != "" && !Entered.value.match("^[0-9A-Za-z ]+$"))
{
alert("Special characters are not allowed");
document.getElementById('<%= EditGroup.ClientID %>').value = '';
}
else
{
}
}
</script>
So if you enter something that is not allowed you will get a message saying "Special characters are not allowed"
This will also stop you page from executing the rest of the code in the button click event.
And you also need to empty the textbox"i know this is maybe not the best way but if you don't empty the textbox and the user will click the button again it will not run the java code because the text didn't change"
So if if the text is good the java script will do nothing and the button click event will fire

Related

Handling multiple UserControls

I have a webpage Containing UserControl repeated 2 times with same functionality. I want to disable the textbox in first UserControl but it is getting disabled in 2nd UserControl.
How to check this?
<script type="text/javascript">
function confirmCallBackFn(arg)
{
if (arg == true)
{
$find('<%= txtOne.ClientID %>').disable();
}
}
Method 1 - If the event is triggered by a control in the parent form
In the user control, you can define a property that returns the ID of the TextBox:
public string TextBoxID
{
get { return txtOne.ClientID; }
}
If your form contains two instances of the user control, ctrl1 and ctrl2, you can target a specific one like this:
document.getElementById('<%= ctrl1.TextBoxID %>').disabled = true;
Note: In the user control, make sure that you don't use ClientIDMode="Static" for the inner controls.
Method 2 - If the event is triggered by an inner control of the user control
If your user control contains the following markup:
<asp:CheckBox ID="chk1" runat="server" />
<asp:TextBox ID="txtOne" runat="server" />
you can add Javascript event handlers to the CheckBox in the Page_Load method of the user control:
protected void Page_Load(object sender, EventArgs e)
{
string js = string.Format("txtBoxID = '{0}';", txtOne.ClientID);
chk1.Attributes.Add("onmousedown", js);
chk1.Attributes.Add("onkeydown", js);
}
These event handlers set the value for a txtBoxID variable that you can define and use in your Javascript block:
<script type="text/javascript">
var txtBoxID;
function confirmCallBackFn(arg) {
if (arg == true) {
document.getElementById(txtBoxID).disabled = true;
}
}
</script>
This method assumes that there is no postback during the process. If a postback occurs, we may have to modify that method and register a script in the event handler in code-behind.

ASP .net PostBack and Function

I'm working on a web page,
I need that when it loads first time it would get data from api's.
Then I want to go from page to page with the same data.
I used IsPostBack
Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//First Time Load Data
leadsList = new List<Lead>();
var client = TVPLeads.Session.GetWebClient(Session);
string PostId = PostId = Request.QueryString["postId"];
PostId = "1";
try
{
leadsList = API.GetPostLeads(client, PostId);
}
catch (Exception) { }
page = (page == 0) ? 0 : page - 1;
DisplayLeadsPage(leadsList, page, "");
}
}
private void pageChoosen(object sender, EventArgs e)
{
int page = int.Parse(((Button)sender).CommandArgument);
DisplayLeadsPage(leadsList, page-1, "");
}
DisplayPagination(){
.
.
Button prev = new Button{
ID = "page_"+i,
CssClass = "Pagination",
Text = "i",
CommandArgument = ""+i,
OnClientClick = "pageChoosen"
};
prev.Click += pageChoosen;
divPagination.Controls.Add(prev);
.
.
.
}
I clicking on a button , got to Page_Load function the postBack is true as expected , but the function is not firing(checked with debugger).
if I remove the IsPostBack and it would make all over again , then the button function is firing.
What's the problem with that? How to use it right ?
The first time you request your page, your page is not posted back. The rendering engine of asp.net creates the page and sends it back to the client.
When you click a button then this click we trigger a postback and a handler that is defined the Page class will execute some code. Then the page will be build and when on Page_Load comes into the scene, the code that is in the if(!Page.IsPostBack) will not be executed, because the IsPostBack property of the Page class is true.
There are two key concepts to conceive there. The first is about the Page lifecycle, the events that the page goes through in each request.
The second is that the Page is not posted back only the first time the client requests it (or the times that she does a full refresh of the page, clicking F5 for instance in Chrome).
Update
Respond to button click
If you haven't defined a server side button, you should define one. How?
In you markup, just add the following line of code:
<asp:Button id="buttonId" Text="Submit" runat="server" />
Then in the designer double click on the button. As you will notice, you will be navigated to the code behind class and a method would have been created, which would be the click handler. Then inside the body of this method, you could write the commands that should be executed, when the user clicks on your button. If you now go back to your markup, you will notice the another attribute would have been added to the Button with name OnClick.
Update
Dynamically built buttons need to be created again when the page is posting back. Otherwise they won't work.
Try adding an event handler to the control.
Your control will look something like this (on the aspx page):
<asp:button id="YourButton" runat="server" OnClick="YourButton_Click" />
Then your backend handler should also be public:
public void YourButton_Click(object sender, System.EventArgs e) {
Edit: You can also do this:
leadsList = new List<Lead>();
if (!Page.IsPostBack)
{
...
}
else
{
page = (page == 0) ? 0 : page - 1;
DisplayLeadsPage(leadsList, page, "");
}
Found an answer for the problem.
When the page is posted back to server.
I need to rebuild the controls Otherwise, those controls will be null.

ASP.Net: How to maintain TextBox State after postback

I would like to know how to maintain the control state that has been modified in Javascript.
I have two TextBoxes, one DropDownList and a button (all Runat=Server) in C# ASP.net 2010 Express.
First textbox is just accept whatever data user input. Second textbox enable state will change based on DDL selected value. If ddl selected value is "-", second textbox will become Enabled = False.
If not "-", it will become Enabled = True. This enable is done through Javascript.
In my Page Load event, I have below code.
if (!IsPostBack)
{
txtKey2.Text = "";
txtKey2.BackColor = System.Drawing.ColorTranslator.FromHtml("#CCCCCC");
txtKey2.Enabled = false;
}
And in my aspx page, I have some javascript which will clear the textbox data and disable the textbox.
Here is for Second Textbox.
<asp:TextBox ID="txtKey2" runat="server" Width="425px" EnableViewState="False"></asp:TextBox>
And here is for DDL.
<asp:DropDownList ID="selKey1" runat="server" onchange="EnableSelkey(this.value,1)">
<asp:ListItem Value="0">-</asp:ListItem>
<asp:ListItem Value="1">AND</asp:ListItem>
<asp:ListItem Value="2">OR</asp:ListItem>
</asp:DropDownList>
Here is the code for my Javascript. (I have a plan to implement other textbox and ddl so in my code I have Else if condition).
function EnableSelkey(val, strID) {
var txtBox;
if (strID == "1")
txtBox = document.getElementById('<%= txtKey2.ClientID %>');
else if (strID == "2")
txtBox = document.getElementById('<%= txtKey3.ClientID %>');
else
txtBox = document.getElementById('<%= txtKey4.ClientID %>');
if (val != 0) {
txtBox.disabled = false;
txtBox.style.backgroundColor = "White";
txtBox.value = "";
txtBox.select();
}
else {
txtBox.disabled = true;
txtBox.style.backgroundColor = "#CCCCCC";
txtBox.value = "";
}
}
I have nothing in button click event.
By using above all code, when I run the project, the page loads Ok.
The second textbox enabled state is set to False (through Page_Load event). So far Ok.
Then from my browser, I choose ddl value to other instead of "-", the textbox become enable because of javascript. This is Ok.
I input the value and click on the button. Page PostBack happens here. Textbox is still enabled (because of EnableViewState = False for my textbox).
I choose ddl value to "-", second textbox became disabled.
Click on the button, page postback happen, but this time the textbox is still enabled. << This is the issue I'm trying to solve. I change EnableViewState, ViewStateMode in different values but still the same.
Is there any solution for this one?
Here is my test image URL.
State 1 ,
State 2 ,
State 3
Sorry for the long post.
I have tried and found no solution beside using additional HiddenField control.
I update the hidden field value when I update the status of my textbox in Javascript.
And on my Page Load event, I checked all the hidden field values and based on the hiddenfield values, I will disable/enable my textboxes which is for me not a good solutions.
Imagine I have 10 or 15 textboxes on my form, I need to have 10 or 15 hidden field just to maintain client side action result.
Currently, this is the only solution for me.
I'm not sure can this consider as 'Answer' so I haven't close this question yet.
<asp:DropDownList ID="selKey1" runat="server" onchange="EnableSelkey(this.value,1)">
<asp:ListItem Value="0">-</asp:ListItem>
<asp:ListItem Value="1">AND</asp:ListItem>
<asp:ListItem Value="2">OR</asp:ListItem>
</asp:DropDownList>
function EnableSelkey(val, strID) {
var txtBox;
if (strID == "1")
txtBox = document.getElementById('<%= txtKey2.ClientID %>');
else if (strID == "2")
txtBox = document.getElementById('<%= txtKey3.ClientID %>');
else
txtBox = document.getElementById('<%= txtKey4.ClientID %>');
if (val != 0) {
txtBox.disabled = false;
txtBox.style.backgroundColor = "White";
txtBox.value = "";
txtBox.select();
}
else {
txtBox.disabled = true;
txtBox.style.backgroundColor = "#CCCCCC";
txtBox.value = "";
}
}
You Have to call you javascript function on every postback.
if (!IsPostBack)
{
txtKey2.Text = "";
txtKey2.BackColor = System.Drawing.ColorTranslator.FromHtml("#CCCCCC");
txtKey2.Enabled = false;
}
ScriptManager.RegisterClientScriptBlock(this, typeof(System.Web.UI.Page), "MyJSFunction", "EnableSelkey("+selKey1.SelectedValue+",1);", true);
It May be help you, Let me know for further help.
I found a solution that worked was to put the code that I put in the !IsPostBack section for enabling and disabling the textboxes also directly in the page load event.

How to call Confirmation box in IF condition from Code-Behind?

I'm using a LinkButton and a DropDown.
When I click on the LinkButton the DropDown appears.
After selecting a DropDown value, I want a confirmation box called from JavaScript to appear, ensuring that the value is changed.
I'm calling this script in the second if condition, but it's not working.
After the confirmation I want to change the other value and exit from the condition.
protected void lnkbtnSave_Click(object sender, EventArgs e)
{
if ((ddlHiringManager.SelectedItem != null &&
(ddlHiringManager.SelectedItem.Text != lblHiringManager.Text)) &&
(Convert.ToInt32(ddlHiringManager.SelectedValue)) != -1)
{
if (ClientScript.RegisterStartupScript(typeof(Page), "Confirm", "<script type='text/javascript'>Confirm('Are you sure you want to change Hiring Manager for this requirement.');</script>"))
{
ClsClientManager objClientManager = new ClsClientManager();
if (objClientManager.UpdateHRManagerByReqID(Convert.ToInt32(hdnReqId.Value), Convert.ToInt32(ddlHiringManager.SelectedValue)) > 0)
{
lblShowHiringManager.Text = ddlHiringManager.SelectedItem.Text;
}
}
}
else
{
ClientScript.RegisterStartupScript(typeof(Page), "SymbolError", "<script type='text/javascript'>alert('Please Select Hiring Manager !');</script>");
}
}
You cannot use the result of RegisterStartupScript method.
Change ASPX page code for the LinkButton as given below
<asp:LinkButton ID="lnkbtnSave" runat="server" OnClick="lnkbtnSave_Click"
OnClientClick="javascript: return confirm('Are you sure you want to change Hiring Manager for this requirement.');">Save</asp:LinkButton>
I have added the client side click event.
On clicking the LinkButton you will get the confirmation box. The page will postback only if you click OK in the confirmation box.
Please refer this Code Snippet. On dropdown selected index change event
protected void ddlTest_SelectedIndexChanged(object sender, EventArgs e)
{
string str = "Are you sure, you want to upload leave ?";
this.ClientScript.RegisterStartupScript(typeof(Page), "Popup", "ConfirmApproval('" + str + "');", true);
}
And for Client Side declare that method.
<script type="text/javascript">
function ConfirmApproval(objMsg) {
if (confirm(objMsg)) {
$('#divUploadLeave').fadeTo('slow', .6);
return true;
} else {
$('#divUploadLeave').fadeTo('slow', 1);
return false;
}
}
Hope It helps you.
Still if you want all things on Client Side please let me know.
Please add return before Confirm this will solve your issue.
**if (ClientScript.RegisterStartupScript(typeof(Page), "Confirm", "<script type='text/javascript'>return Confirm('Are you sure you want to change Hiring Manager for this requirement.');</script>"))**

problem with check box in asp .net c#?

The controls on aspx page are like this
Submitted
Submission Date
I want, if the check box is checked, then the textbox will be enabled I wrote
if(chkSubmitted.Checked)
{
txtSubmissionDate.Enabled = true;
}
in the page load event. But when the page is loaded this checkbox having no effect on. Whats going wrong?
If you want the action of clicking the checkbox to enable the textbox, you'll need to do a postback when the box is checked by setting AutoPostBack="True":
<asp:CheckBox runat="server" ID="chkSubmitted" AutoPostBack="True" />
Or, you could use JavaScript:
<asp:CheckBox runat="server" ID="chkSubmitted" onclick="setSubmissionDateEnabled()" />
function setSubmissionDateEnabled()
{
var chkSubmitted = document.getElementById("<%= chkSubmitted.ClientID %>");
var txtSubmissionDate = document.getElementById("<%= txtSubmissionDate.ClientID %>");
txtSubmissionDate.disabled = !chkSubmitted.checked;
}
First set autopostback property to true of checkbox
write following code in checkbox_Selectedindexchanged event
if(chkSubmitted.Checked)
{
txtSubmissionDate.Enabled = true;
}
else
{
txtSubmissionDate.Enabled = false;
}
Thats most likely because the default state of txtSubmissionDate is enabled already.
Try this in your page_load:
txtSubmissionDate.enabled = !chkSubmitted.Checked
To clarify, the textbox should not (!) be enabled when the Checkbox is.
Put this in Page_PreRender event. At this stage it will capture the user affected state of chkSubmitted.

Categories