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

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>"))**

Related

Having to click button twice to trigger postback in asp.net

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

disable dropdownlist on page load

I have 2 dropdownlists populated from database:
what I want is to disable the second one on page load and when the value of the first one =="1".
here is my second dropdownlist:
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True"
DataSourceID="SqlDataSource2" DataTextField="BName" DataValueField="BId"
OnDataBound="DownList2_DataBound"
OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged">
</asp:DropDownList>
This what I tried to disable the dropdownlist2 (javascript):
<script type="text/javascript">
window.onload = function () {
document.getElementById('DropDownList2').disabled = true;
}
</script>
Tried another thing in C# code:
protected void Page_Load(object sender, EventArgs e)
{
if (DropDownList1.SelectedValue.ToString() == "1")
{
DropDownList2.Enabled = false;
}
}
I even tried this alone in page_load:
DropDownList2.Enabled = false;
The problem is it's disabled on SelectedIndexChanged for dropdownlist1 but not on page load! Is there's something missing in my code?
This statement allow you to set the dropdown2 to disable at page load.
$('#' + '<%=DropDownList2.ClientID%>').attr('disabled',true);
you can do this using Jquery simply as follow:
$(document).ready(function () {
var isPostBack = '<%=IsPostBack%>';
if (isPostBack == 'False' || $('#' + '<%=DropDownList1.ClientID%>').val() == '1') {
//This statement allow you to set the dropdown2 to disable
$('#' + '<%=DropDownList2.ClientID%>').attr('disabled', true);
}
else {
$('#' + '<%=DropDownList2.ClientID%>').attr('disabled', false);
}
$('#' + '<%=DropDownList1.ClientID%>').on("change", function () {
//Your code here
if ($('#' + '<%=DropDownList1.ClientID%>').val() == '1') {
$('#' + '<%=DropDownList2.ClientID%>').attr('disabled', true);
}
else {
$('#' + '<%=DropDownList2.ClientID%>').attr('disabled', false);
}
});
});
It is likely that the DropDownList1.SelectedValue is not equal to "1" on Page Load as I guess you'd be DataBinding it somehow, which would take effect afterwards.
Try adding a SelectedIndexChanged function for DropDownList1 and dis/enabling DropDownList2 here. You can put Enabled="False" in the markup for DropDownList2 to ensure it starts off Disabled.
The issue is likely that document.getElementById('DropDownList2') doesn't find your dropdown list. The ID for the list is a server-side value that doesn't necessarily translate to the client-side ID. If you set ClientIDMode for the control to Static, then the client ID will be DropDownList2. Another option is to access the ClientID property of the control when outputting your JavaScript (if it's inline):
document.getElementById('<%=DropDownList2.ClientID%>').disabled = true;
All that being said, even if that's the case, it'd be better to just start with Enabled="False" as #aaroncatlin suggests so you don't have to wait for the JavaScript to execute before it is disabled.
in ASP.NET the generated ID differs from the asp ID on the component, to access the element from Javascript you need to use <%=DropDownList2.ClientID%> the corresponding javascript will be something like this :
document.getElementById(<%=DropDownList2.ClientID%>).disabled = true;
The DropDownList would have a default selected index of -1 and a null value for selected value. I usually check against the selected index, instead of by value. For example,
if(DropDownList1.SelectedIndex < 1){
// assuming that index 0 holds your value of "1"
DropDownList2.Enabled = false;
}
And #Jacob did rightly point out about you needing to get the proper ClientID for your JavaScript function.

How do I use the hyperlink field in gridview, a new pop-up, to link back to my main page

I have created a page with a button that opens up a new page, a pop-up if you will.
btnToolbarSearch.Attributes.Add("onclick", "window.open('DagbokSearch.aspx','','height=600,width=600');return false");
On this new page that opens up I have a gridview where you get the below info. (You do a search on the "from date" to the "to date" and get the records in between.)
The first column where it says "Gå till" is a link
<asp:HyperLinkField DataNavigateUrlFields="Foretag"
DataNavigateUrlFormatString="userProfile.aspx?ID={0}"
Text="Gå till" />
I would like this link to get me back to the previous page and open up the object with the corresponding id, I'm not sure how to accomplish this. Maybe there is a better way then the one I'm using but I'm still learning.
You should be able to use the window.opener property to get a reference to the parent window. You can then set it's URL to the selected link, and close the popup window.
Something like this should do the trick:
// Place this near your closing </body> tag
// NB Uses jQuery and event delegation
$(function() {
$('table').on('click', 'tr > td:first > a', function(event) {
if (window.opener) {
event.preventDefault();
window.opener.location.href = this.href;
window.close();
}
});
});
You can set its NavigateUrl property in the Rowdatabound event of the gridview. Like;
protected void gvDogBok_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
((HyperLink)e.Row.Controls[1].Controls[1]).NavigateUrl = "~/userProfile.aspx?ID="+((YourType)e.Row.DataItem).ID+"";
}
}
I'm not sure if what you are asking can be done. I would advice you to use a floating div popup instead. This way you dont have to leave the current page and go to a new tab. This should solve your problem and does avoid problems with popup blockers.
Here are some examples: http://www.javascripttoolbox.com/lib/popup/example.php
Use this one
protected void gvDogBok_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
((HyperLink)e.Row.Controls[1].Controls[1]).Attribute.Add("onclick", "window.opener.location =userProfile.aspx?ID="+ ((YourType)e.Row.DataItem).ID+"; window.close();";
}
}
You can set JavaScript:window.location.replace(url); to the clientside onclick of the HyperLink. window.location.replace(url) will reload the page.
btnToolbarSearch.Attributes.Add("onclick", "var windowHandle = window.open('DagbokSearch.aspx','','height=600,width=600');return false");
and on hyperlink cleint side onclick
hyperLink.Attributes.Add("onclick", "windowHandle.close();window.location.replace(url);return false");

Fire JavaScript from button inside GridView

I have a GriView and implemented RowDataBound event like below
protected void gvwSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int index = e.Row.RowIndex;
string IdValue = gvwSearchResult.DataKeys[index].Value.ToString();
Button _btnCheque = (Button)e.Row.FindControl("btnCheque");
_btnCheque .OnClientClick = "<script type='text/javascript'>if(confirm('Do you want to continue?')){window.location='Cheque.aspx?ID=" + IdValue.ToString()+"';}</script>";
}
}
When I click on button, there is a script error thrown. any idea on my script formatting?
What is the error you are getting?
Try using the same without the <script> tag (see example in MSDN)...
You don't need the script tags in the OnClientClick - just put the javascript directly.

Do not show confirm messagebox if gridview checkbox is not checked

I have gridview which has columns of data and a button below the "Apply" to perform some action.
One column in Gridview is a checkbox column. When you select checkboxes and click apply a confirm message pops up asking "Are you sure?" with option of "Yes" and "No".
But if no check box is checked i want to show a popup to user to select a checkbox before performing an action and not show the confirm message popup.
What i have now is if no checkbox is selected the confirm message pops up first and if i press "yes" then an alert message pops up to select atleast one checkbox. If i press cancel no pop up shows.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ApplyAction_Button.Attributes.Add("onclick", "return confirm('Are you sure?');");
}
}
protected void ApplyAction_Button_Click(object sender, EventArgs e)
{
// Gets the selected checkboxes in the gridview
ArrayList selectedMachines = new ArrayList();
GetSelectedMachineIds(selectedMachines);
if (selectedMachines.Count == 0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "<script>alert('Please select a machine for the action to be applied');</script>");
return;
}
// Action to be applied
}
I am trying to avoid the use of postback.
Another question:
Is there a server side confirm message box in asp.net?
Any help will be appreciated. Thanks
You can set your button visible to false, once check box is checked then you can show the button.
another way is to use javascript to check if checkbox is checked
code behind
ApplyAction_Button.Attributes.Add("onclick", "ShowConfirm();");
javascript
function ShowConfirm()
{
//check if checkbox is checked if is checked then display confirm message else display alert message
if( "assumed checkbox is checked"){
return confirm("message here");
}
else{
alert("message here");
}
}
try to see this thread
Checkbox in gridview
Determining a which checkbox is checked on a datagrid and updating DB
Regards

Categories