From my code behind, in my update method, I have to ask the user if he wants to overide some particular value. If so, overide, if not, continue with the saving without saving this value.
In my aspx I have this javascript function:
function ConfirmationBox(msg) {
var ovd = document.getElementById("hdnOveride"); //gets a HiddenField
if (confirm(msg) == true) {
ovd.value = "1";
return true;
}
else {
ovd.value = "0";
return false;
}
}
From codebehind, I call this function. And then I check the value of my HiddenField "hdnoveride". If its 1 I save, otherwise I don't.
System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Test", "javascript:ConfirmationBox('overide?');", true);
if (hdnOveride.Value == "1"){
//Save the value
}
The problem is that my code doesn't wait for the user to answer the confirm box before it continues. I have tried using Thread.Sleep() while hdnOveride is not set like this:
while (hdnOveride.Value == "notset") {
System.Threading.Thread.Sleep(500);
}
But it just stops everything, so the popup box never shows when I do this.
How can I tell the system to wait for an answer before continuing with the code?
Thanks!
Ok then, I used Panel instead to ask the question to my users as suggested here: https://stackoverflow.com/a/7677000/454157
Related
I want the MessageBox in this code to be run only 1 time. I want it to be shown only one time. How can I do it?
if(textBox1.Text != "")
{
listBox1.Items.Add(textBox1.Text);
textBox1.Clear();
}
else
{
DialogResult click = MessageBox.Show("Info Screen", "TextBox is Empty. Do you want to add a
blank space?", MessageBoxButtons.OKCancel);
if(click==DialogResult.OK)
{
listBox1.Items.Add(textBox1.Text);
}
}
Make a boolean and use an if statement and inside that if statement make the boolean false and show your message box
bool boolMessage = true;
if(boolMessage == true)
{
MessageBox.Show("One time");
boolMessage = false;
}
Create a global variable of type boolean and save the mark if the message has been shown. Then in your code add
Global:
bool isFirstTime = true;
In your code:
if (isFirstTime) {
DialogResult click = MessageBox.Show("Info Screen", "TextBox is Empty. Do you want to add a
blank space?", MessageBoxButtons.OKCancel);
isFirstTime = false;
}
I think adding a boolean flag in your case is just code pollution. You can solve this problem the other way. => When do you want the MessageBox to be displayed? When the textbox content equals "" and you want this to run only once. Why not to check if there is already an "" within the listbox before displaying the messagebox? Something like this:
else
{
if(listbox1.Items.IndexOf("") > -1)
return;
// continue with displaying the messagebox
}
Try using a boolean and use an if to make sure that the code runs only if the Boolean is true, then, inside the if just set the Boolean to false.
You can try also using a function and calling it once.
I am not sure if I answered your question.
I am perplexed, and maybe I am just familiar with the properties of pageLoad, IsPostBack, or IsCallback. I created a Boolean variable called "first" and set it to True.
First time through PageLoad, there is a line of code if first = False, if so, write = true.
Then I have a Run_write routine attached to a button, when it runs, if the user response Yes, to the initial question, I make another group of radio buttons visible and set first to false. (i ran this in debug, and I know it hits this line of code) ... so the write to sql is ignored because write == false and the window reappears with the new set of Buttons... Great!
Furthermore, I go through the PageLoad routine again, and it hits the line if (!first), set write to TRUE. my issue is first has been re-set to true? What am I missing?
Note, I was able to work around this by utilizing whether the new set of buttons is checked, but I may not want to go this route, and I do want to understand what is going on.
code is below.
namespace MEAU.Web.Components.SupportCenter
{
public partial class feedback : System.Web.UI.Page
{
String login;
String myurl;
String response;
String s_call;
String p_ship;
String wrnty;
Boolean write;
Boolean first = true;
protected void Page_Load(object sender, EventArgs e)
{
login = Sitecore.Security.Accounts.User.Current.Profile.Email;
myurl = Request.QueryString["value"];
s_call = "No";
p_ship = "No";
wrnty = "No";
// Hide the question Buttons
scall.Visible = false;
parts.Visible = false;
wrnt.Visible = false;
lit.Visible = false;
write = false;
if (!first)
write = true;
}
protected void Run_Write(object sender, EventArgs e)
{
// Get Reponse
if (yes.Checked)
{
response = "Yes";
// Display the quesiton buttons, and Hide the NO button
scall.Visible = true;
parts.Visible = true;
wrnt.Visible = true;
lit.Visible = true;
no.Visible = false;
first = false;
// Did this Prevent a Service call?
if (scall.Checked)
{
s_call = "Yes";
write = true;
}
// Did this Prevent a parts shipment?
if (parts.Checked)
{
p_ship = "Yes";
write = true;
}
// Is this under warranty?
if (wrnt.Checked)
{
wrnty = "Yes";
write = true;
}
// write = true;
}
if (no.Checked)
{
response = "No";
write = true;
}
if (write == true)
{
SqlConnection conn = new SqlConnection(Sitecore.Configuration.Settings.GetConnectionString("feedback"));
SqlCommand cmd = new SqlCommand("Insert_fb", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#login", login);
cmd.Parameters.AddWithValue("#url", myurl);
cmd.Parameters.AddWithValue("#response", response);
cmd.Parameters.AddWithValue("#dateTime", DateTime.Now);
cmd.Parameters.AddWithValue("#serviceCall", s_call);
cmd.Parameters.AddWithValue("#partsShipment", p_ship);
cmd.Parameters.AddWithValue("#warranty", wrnty);
try
{
conn.Open();
cmd.ExecuteNonQuery();
Response.Write("<script type='text/javascript'>parent.$.fancybox.close();</script>");
Response.Write("<script type='text/javascript'>return false;</script>");
}
catch (Exception ex)
{
throw new Exception("Error on file update" + ex.Message);
}
finally
{
conn.Close();
}
}
}
}
}
Every HTTP request to your site creates a new instance of your page class.
Instance state is not preserved.
Instead, you need to store the state in session or ViewState, depending on what you want to apply to.
Page_Load will be called every time your server is requested for the page. This includes post-backs.
You can check IsPostBack to see if the current Page_Load execution is for the first display of the page, or a subsequent post-back.
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
// Do first-time things
}
else
{
// Do non-first-time things
}
}
Note that the particular instance of your page object will not persist from access to access. So there may be some information that you need to initialize every time the page is called.
Every time you visit the page, you're creating a new instance of the class.
To distinguish a page load from a user clicking a button vs. a user arriving on the page for the first time, you want to check the IsPostBack property.
So rewrite your if along the lines of
// Code that always executes
if (IsPostBack)
{
// Code that only executes on initial page load
}
else
{
// Code that only executes when a postback event occurs
// e.g. A user clicks on a button.
}
There are some ways by which you can maintain the state or value of the controls, so I have been maintaining the Viewstate of the controls in the not is postback, as check of
(!IspostBack) // means when page loads first time
and whatever written in the else means when postback occurs in which you can maintain the viewstate of the objects.
Also we can use the session, if Viewstate is not used.
Rykiel,
the basic concept of the web is (state-less), and that why you have to handling, but anyway you can read about page life cycle I recommend you read it http://www.codeproject.com/Articles/20659/The-ASP-NET-Page-Lifecycle-A-Basic-Approach
you can use
if(!isPostBack)
{
first=true;
this portion of code only run when the page is requested first time
}else
{
first = false;
}
if you change the value of control in the page or click a button isPostBack will be true. but if you refresh the page or hit F5 you page will be requested again and isPostBack will be false;.
also you can use cookies or session variable (I also recommend do not load too much the Session Variable). try to read the prior link and you will be more clear where put your code to get the best performance.
J.S.
The answers on here are good, but technical. I will try to explain a little of what is happening.
When a browser requests your page, and on the server, a new instance of your class is created.
ASP.NET then runs the rest of the page, starting with your page_load. This will call all your other functions and then render the HTML as a response to your request and send it back to the browser. I like to explain this as a disconnected environment. Once the response is sent, everything is disposed of in a sense. Your variables, previous work, etc... are all gone. The Server as far as it is concerned, never expects to get anything from the browser again... its done its job. It took your request for a page, created a result and posted it back to the browser. Done.
So, think of your code as a new request each time it is called.
You can use the IsPostback as stated by ThatBlairGuy, because that will return true if you are responding to a postback from the browser, meaning that it has already served up this page to the browser on the previous postback.
I need to callback Javascript function in my code, but not firing. I am providing details what I am doing?.
I have input button in the page that calling javascript function. There I am loading another ProfilePic.aspx page. ProfilePic.aspx has FileUpload, OK and cancle button
<input type=button value="Change Image" onclick="javascript:SelectUserImage()" />
Javascript functions are
<script type="text/javascript">
function SelectUserImageCallback(ret) {
var imgId = 'ctl00_PlaceHolderMain_prof_imgUser';
var clearId = 'ctl00_PlaceHolderMain_prof_hidImageURL';
if (ret) {
if (ret == '__RESET__') {
document.getElementById(imgId).src = '\u002f_layouts\u002fimages\u002fno_pic.gif';
document.getElementById('ctl00_PlaceHolderMain_prof_hidImageURL').value = '';
document.getElementById(clearId).style.display = 'none';
}
else {
document.getElementById(imgId).onload = 'imgResizeMax(\'ctl00_PlaceHolderMain_prof_imgUser\', 100);imgResizeTbl(\'ctl00_PlaceHolderMain_prof_imgUser\');';
document.getElementById(imgId).src = ret;
document.getElementById('ctl00_PlaceHolderMain_prof_hidImageURL').value = ret;
setTimeout('imgResizeMax(\'ctl00_PlaceHolderMain_prof_imgUser\', 100);imgResizeTbl(\'ctl00_PlaceHolderMain_prof_imgUser\');', 1);
setTimeout('imgResizeMax(\'ctl00_PlaceHolderMain_prof_imgUser\', 100);imgResizeTbl(\'ctl00_PlaceHolderMain_prof_imgUser\');', 100);
document.getElementById(clearId).style.display = '';
}
}
}
function SelectUserImage() {
var href = '\u002f_layouts\u002fProfilePic.aspx';
var features = 'resizable: yes; status: no; scroll: no; help: no; center: yes; dialogWidth: 460px; dialogHeight: 140px; width:460;height:240;menubar:no;directories:no;location:no;';
commonShowModalDialog(href, features, SelectUserImageCallback, null);
}
In the ProfilePic.aspx page once user click OK buttong. I am upload his pic with some logic then I am closing window with javascript
protected void btnOK_Click(Object sender, EventArgs e)
{
try
{
// My logic Here
Debug.WriteLine("Shared Pictures Save Ends: " + DateTime.Now);
Response.Write ("<script language =javascript>close();</script>");
Response.End();
}
catch (Exception exception)
{
LogMessage(exception.Message, EventLogEntryType.Error);
if (exception.Message.ToLower().Contains("blocked"))
errorDisplay.Text = "* This type of file has been blocked by the administrator, please try a different file.";
else
{
errorDisplay.Text = exception.Message;
}
}
}
My Question: I am able to close the window but, What ever I need to call callback function `SelectUserImageCallback' not firing. I need to call this method after OK button part execution done.
Are you closing the window before the callback executes? I've done that before. As an experiment, try commenting out the code that closes the window.
You may have to restructure your code so that the callback function closes the window when it's finished whatever it's doing.
Update: Sorry, I misunderstood the question. There was a lot of code and I didn't read it all. I thought the call back was in the dialog page, but it looks like it's in the main page. I'm not familiar with commonShowModalDialog(), but it looks like it may have something to do with SharePoint. Do you have any documentation on that method? I found this discussion that makes it look like there's a special way to return a value from the dialog box. It may be that your callback isn't being called because you're not closing the window the right way. (That's a total guess on my part.)
Good luck.
i have a webform that generates a file, but when i click the button that produces the postback to generate the file Once it finish if i press Refresh (F5) the page resubmit the postback and regenerates the file, there's any way to validate it and show a message to the user or simply DO NOTHING!
thanks :)
The simpler way will be to use Post Rediret Get pattern.
http://en.wikipedia.org/wiki/Post/Redirect/Get
Make sure to check out External Links on that Wikipedia article.
the browser should warn them if they hit refresh on a page that has been postbacked. how i handle it though is in the session track what i have done so i don't repeat certain actions. a simple flag should suffice.
Check for the existence of the file in question in your postback logic and only create the file if the file doesn't already exist:
if (false == System.IO.File.Exists(filename))
{
// create the file
}
else
{
// do whatever you do when the file already exists
}
i wrote a solution for this problem and here it is if anyone needs it.
protected void Page_Load(object sender, System.EventArgs e)
{
/*******/
//Validate if the user Refresh the webform.
//U will need::
//A global private variable called ""private bool isRefresh = false;""
//a global publica variable called ""public int refreshValue = 0;""
//a html control before </form> tag: ""<input type="hidden" name="ValidateRefresh" value="<%= refreshValue %>">""
int postRefreshValue = 0;
refreshValue = SII.Utils.convert.ToInt(Request.Form["ValidateRefresh"]); //u can use a int.parse()
if (refreshValue == 0)
Session["ValidateRefresh"] = 0;
postRefreshValue = SII.Utils.convert.ToInt(Session["ValidateRefresh"]); //can use a int.parse()
if (refreshValue < postRefreshValue)
isRefresh = true;
Session["ValidateRefresh"] = postRefreshValue + 1;
refreshValue = SII.Utils.convert.ToInt(Session["ValidateRefresh"]); //can use a int.parse()
/********/
if (!IsPostBack)
{
//your code
}
}
you just have to evaluate:
if (!isRefresh)
PostFile();
else
{
//Error msg you are refreshing
}
So I'm trying to make a folderbrowser for my custom application in C# and the folderbrowser thing is okay, but I want to set it up like how the default one acts.
According to #Kevin I am trying to make a modal dialog.
// I create the folderbrowser control and await the directory
string CreateFileDialog(bool allowFixedDrives)
{
FolderBrowser fb = new FolderBrowser(this, allowFixedDrives);
fb.Show();
//return THE_SELECTED_FOLDER_DIR;
return "";
}
So in the folderbrowser there is a boolean to allow fixed drives and also a reference to the parent form:
// Create the control and receive whether or not it should read fixed drives and also get a reference to the parent control.
public FolderBrowser(Form1 frm1, bool allowFixed)
{
InitializeComponent();
this.allowFixed = allowFixed;
frm1.Enabled = false;
}
I freeze the main form when this dialog is created. If the user closes the form, it will return null or "" and if the user presses okay, it should return the selected directory (where THE_SELECTED_FOLDER_DIR is).
Does anyone know how I can cleanly implement a dialog that sends feedback to the parent form?
Feel free to ask if you are as confused as I am :)
So after a rather interesting discussion with #Kevin, I've decided that the best way to go about this would be to call a public function in the form and then show it. Kinda hard to explain, so I'll show you:
NB: I think this should be kept open just in case someone has the same issues I did...
So I want to simply get a selected folder name and I'll display that selected folder on a text control for example:
bool invalid = false;
string value = CreateFileDialog(true, out invalid);
if (!invalid)
{
txt_File.Text = value;
}
else
{
MessageBox.Show("A folder was not selected.");
}
Okay, so I'm creating a dialog. I check if the dialog was closed without selecting a file and display a messagebox if it's invalid....
string CreateFileDialog(bool allowFixedDrives, out bool invalid)
{
FolderBrowser fb = new FolderBrowser(this, allowFixedDrives);
return fb.ShowForm(out invalid);
}
Now here is where it gets interesting. I create the dialog here and call a function on the form to actually show it, but I pass a boolean as an out variable to detect if it was closed without selecting a file.
And finally:
public string ShowForm(out bool a)
{
ShowDialog();
frm1.Enabled = true;
if (!Directory.Exists(selectedFolder))
{
a = true;
return selectedFolder;
}
else
{
a = false;
return selectedFolder;
}
}
I return the selected folder name if the user pressed OK, otherwise don't return it and also set the out parameter to false.
There you have it.
I'd like to thank everyone who pitched in here, namely #Kevin.