When I use checkbox with a postback, my main class starts again at the first line. Therefore my variable changes again.
Like this:
public partial class Fırın1 : System.Web.UI.Page
{
bool Checkboxlist1value, Checkboxlist1value = false;
bool first_value=false;
protected void Page_Load(object sender, EventArgs e)
{
Panel1.Visible = false;
if (!Page.IsPostBack)
{
first_value = true;
}
}
}
As you can see in a small section of my code, when I click checkbox or save button class fırın_1 starts again at the first line. Thus first_value changes to false. But I need true because the condition will change this value to true.
How can I solve this problem?
Thanks in advance for your cooperation.
If you want to persist values across a PostBack, you should generally store them in ViewState.
If I understand what you're trying to achieve, you should change first_value from a field to a property that's backed by ViewState. For example (I've changed it from first_value to FirstValue in line with Microsoft guidelines):
public bool FirstValue
{
get
{
object o = ViewState["FirstValue"];
if (o == null) return false; // default is false
return (bool) o;
}
set
{
ViewState["FirstValue"] = value;
}
}
...
protected void Page_Load(object sender, EventArgs e)
{
Panel1.Visible = false;
if (!Page.IsPostBack)
{
FirstValue = true;
}
}
Related
Goal: Keep value of int (professorIndex) reachable when I get to the button click method (btnUpdateAvailability_Click())
Problem: The value gets set correctly initially, then somehow goes to 0
What ive tried: Starting variable at class level. Getting rid of any other references to it, including commenting out where it was set to 0
What am I missing?
C#:
public partial class SiteMaster : MasterPage
{
private int professorIndex;
protected void Page_Load(object sender, EventArgs e) {
//some stuff
}
protected void cbUpdateAvailability_Click(object sender, EventArgs e)
{
CheckBox cbSender = (CheckBox)sender;
professorIndex = getProfessorIndexCB(cbSender.ClientID);
//at this point, professorIndex is 1, which is what I want/expect
}
public int getProviderIndexCB(string cbSender)
{
//professorIndex = 0;
switch (cbSender)
{
case "chkOnOff1":
professorIndex = 0;
break;
case "chkOnOff2":
professorIndex = 1; //This is the one that is triggered
break;
}
return professorIndex;
}
protected void btnUpdateAvailability_Click(object sender, EventArgs e)
{
//at this point, professorIndex is 0, no clue why. It should be one
}
Below a simple demo to store a value you want to persist in a Session and get it back on PostBack.
public int professorIndex = 0;
protected void Page_Load(object sender, EventArgs e)
{
//check for postback
if (!IsPostBack)
{
//set the index
professorIndex = 10;
//store the index in a session
Session["professorIndex"] = professorIndex;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//check if the session exists
if (Session["professorIndex"] != null)
{
//cast the session back to an int
professorIndex = (int)Session["professorIndex"];
}
//show result
Label1.Text = $"The professor index is {professorIndex}.";
}
In my Program I have a button click, from that onclick event I am calling one method for some textbox validation. The code is:
protected void btnupdate_Click(object sender, EventArgs e)
{
CheckValidation();
//Some other Code
}
public void CheckValidation()
{
if (txtphysi.Text.Trim() == "")
{
lblerrmsg.Visible = true;
lblerrmsg.Text = "Please Enter Physician Name";
return;
}
//Some other Code
}
Here if txtphysi.text is null then it comes into loop and use return then it came from the CheckValidation() method only and it continues in btnupdate_Click event, but here I want to stop the execution process in btnupdate_Click also. How can I do it?
It is very simple programming logic in my understanding that you need to apply here..
That is return Boolean from CheckValidation() method instead of return void so that parent function knows the state from the function's execution.
protected void btnupdate_Click(object sender, EventArgs e)
{
var flag = CheckValidation();
if(!flag)
return;
//Some other Code
}
public bool CheckValidation()
{
var flag = false; // by default flag is false
if (string.IsNullOrWhiteSpace(txtphysi.Text)) // Use string.IsNullOrWhiteSpace() method instead of Trim() == "" to comply with framework rules
{
lblerrmsg.Visible = true;
lblerrmsg.Text = "Please Enter Physician Name";
return flag;
}
//Some other Code
flag = true; // change the flag to true to continue execution
return flag;
}
To achieve this:
1) Change the return type of the CheckValidation() method to bool. In your btnupdate_Click() method do something along the lines of
if(!CheckValidation())
{
return;
}
Hope that helps.
If this is ASP.NET, which you have tagged it as, then you should perhapts use a RequiredFieldValidator (for webforms), and you could use DataAnnotations if you are using MVC: http://forums.asp.net/t/1983198.aspx?RequiredFieldValidator+in+MVC
Though answer has been already accepted, but I believe this is not good practice to put code in events. Better to use delegates for such purposes.
public class Sample
{
public Sample()
{
UpdateAction = OnUpdate;
}
Action UpdateAction = null;
private void OnUpdate()
{
//some update related stuff
}
protected void btnupdate_Click(object sender, EventArgs e)
{
CheckValidation(UpdateAction);
}
public void CheckValidation(Action action)
{
if (txtphysi.Text.Trim() == "")
{
lblerrmsg.Visible = true;
lblerrmsg.Text = "Please Enter Physician Name";
return;
}
action();
}
}
Here try this:
protected void btnupdate_Click(object sender, EventArgs e)
{
if(!CheckValidation())
{
//Some other Code
}
}
public bool CheckValidation()
{
if (string.isnullorEmpty(txtphysi.Text.Trim()) )
{
lblerrmsg.Visible = true;
lblerrmsg.Text = "Please Enter Physician Name";
return false;
}
else
{
//Some other Code
return true;
}
}
I'm fairly new to programming so sorry if this is simple, but I might just be missing the obvious! I have the following form which is automatically populated on load from settings stored in an INI file:
The whole form is working just as I want it to apart form one small part. The 'Close' button currently just closes the form so that if any values have changed in the text boxes since the form was loaded, the changes are lost. I want to instead prompt the user to use the Save button instead otherwise the changes will be lost.
I've been trying to do something along these lines on my close button where the value of the text boxes are checked against the variable values that they were originally populated with:
private void btnClose_Click(object sender, EventArgs e)
{
if (txtName.Text != name || txtSchName.Text != schname || txtServer1.Text != svr1 etc etc etc)
{
Warn User changes will be lost, ask user if really OK to close?
if (User chooses to to close)
{
this.Close();
}
else
{
Go back to the config form;
}
}
else
{
this.Close();
}
With over 21 text fields, I was not sure if this was the most "tidy way" of checking for changes? Any pointers would be appreciated.
You just add a global boolean variable and write an handler for the TextChanged event
// Declared at the form level
private bool _modified = false;
public Form1()
{
InitializeComponent();
// This could be done in the form designer of course
// o repeated here for every textbox involved....
txtName.TextChanged += OnBoxesChanged;
......
}
private void Form1_Load(object sender, EventArgs e)
{
.....
// Code that initializes the textboxes could raise the TextChanged event
// So it is better to reset the global variable to an untouched state
_modified = false;
}
private void OnBoxesChanged(object sender, EventArgs e)
{
// Every textbox will call this event handler
_modified = true;
}
private void btnClose_Click(object sender, EventArgs e)
{
if(_modified)
{
// Save, warning, whatever in case of changes ....
}
}
Just set the event handler OnBoxesChanged for every textbox you want to trigger the condition. You could do it through the Designer or manually after the InitializeComponent call
What you are looking for is Dirty Tracking. Dirty tracking is used to track states of your control. Here is a simple reusable approach to track your controls
public class SimpleDirtyTracker
{
private Form _frmTracked;
private bool _isDirty;
public SimpleDirtyTracker(Form frm)
{
_frmTracked = frm;
AssignHandlersForControlCollection(frm.Controls);
}
// property denoting whether the tracked form is clean or dirty
public bool IsDirty
{
get { return _isDirty; }
set { _isDirty = value; }
}
// methods to make dirty or clean
public void SetAsDirty()
{
_isDirty = true;
}
public void SetAsClean()
{
_isDirty = false;
}
private void SimpleDirtyTracker_TextChanged(object sender, EventArgs e)
{
_isDirty = true;
}
private void SimpleDirtyTracker_CheckedChanged(object sender, EventArgs e)
{
_isDirty = true;
}
// recursive routine to inspect each control and assign handlers accordingly
private void AssignHandlersForControlCollection(
Control.ControlCollection coll)
{
foreach (Control c in coll)
{
if (c is TextBox)
(c as TextBox).TextChanged
+= new EventHandler(SimpleDirtyTracker_TextChanged);
if (c is CheckBox)
(c as CheckBox).CheckedChanged
+= new EventHandler(SimpleDirtyTracker_CheckedChanged);
// ... apply for other desired input types similarly ...
// recurively apply to inner collections
if (c.HasChildren)
AssignHandlersForControlCollection(c.Controls);
}
}
and in your mainform
public partial class Form1 : Form
{
private SimpleDirtyTracker _dirtyTracker;
private void Form1_Load(object sender, EventArgs e)
{
_dirtyTracker = new SimpleDirtyTracker(this);
_dirtyTracker.SetAsClean();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// upon closing, check if the form is dirty; if so, prompt
// to save changes
if (_dirtyTracker.IsDirty)
{
DialogResult result
= (MessageBox.Show(
"Would you like to save changes before closing?"
, "Save Changes"
, MessageBoxButtons.YesNoCancel
, MessageBoxIcon.Question));
}
}
If you want to save for example usersettings you could create Settings in your Properties.
You can get them like this:
string anyProperty = WindowsFormsApplication1.Properties.Settings.Default.TestSetting;
You save them using the Save-method:
WindowsFormsApplication1.Properties.Settings.Default.TestSetting = "Hello World";
WindowsFormsApplication1.Properties.Settings.Default.Save();
You can call the Save-method after you have clicked the close-button.
For saving several string properties you could create a property of the type System.Collections.Specialized.StringCollection, so that you just create one property and not 21.
One disadvantage of dirtytracer is, that it returns "dirty" even when changes revert to original state. If You use object in DataContext as Your data model, all this task simplifies to:
bool changed = dataContext.SomeTables.GetModifiedMembers(someRow).Any();
I've seen this problem a lot, and it's usually because the ViewState variables are being evaluated too early in the page lifecycle, or that EnableViewState is false, but I've checked for both of these and they are as I'd expect them to be.
My code:
public Int32 MyNumber
{
get
{
if (ViewState["MyNumber"] != null)
{
return (Int32)ViewState["MyNumber"];
}
return 0;
}
set
{
ViewState["MyNumber"] = value;
}
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!this.IsPostBack)
{
MyNumber = 23;
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
var numberValue = MyNumber;
}
When OnPreRender is first called, numberValue is 23. Every subsequent call thereafter it's 0. Every time there's a postback it appears to get reset.
Question
How do I get the value to persist after a postback?
What I've Tried
Bringing the value assignment outside of the check for a postback, but then that defeats the purpose of using ViewState in the first place.
I was unaware there was also a ViewStateMode that would cause this behaviour if set to Disabled, which it was (on the master page).
I've now set that to Enabled on my control, and my ViewState values persist as I'd hope.
actually you have a missing order in your code block excaution and that makes the value reset by zero everytime between post packs :) ... in the onload Method you wrote the base.onload() method before your code block and that lead the Viewstate to be reset to 0 .
Please fellow that code correction:
public Int32 MyNumber
{
get
{
if (ViewState["MyNumber"] != null)
{
return (Int32)ViewState["MyNumber"];
}
return 0;
}
set
{
ViewState["MyNumber"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(MyNumber.ToString()); // Result now is 23 :)
}
protected override void OnLoad(EventArgs e)
{
// I replaced the order of the code here to get the value of the Viewstate in MyNumber property ..
if (!this.IsPostBack)
{
MyNumber = 23;
}
base.OnLoad(e);
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
var numberValue = MyNumber;
}
Good Luck :).
I'm creating a web user control in asp.net using C# in which i can select a date from a calendar and display it in a textbox. when i select a date from the calender it has to be displayed in the textbox.
now i need to set my own properties by which i can select datetime patterns in cs codefile. for example
usercontrol1.dd-mm-yyyy.
this is one example. now i want all the datetime patterns of "en-us". when i use that usercontrol in another page i want to set any of the properties(datetime patterns) to that control. please help me!!!
i tried this coding but no use... plz review it and give me solution
public partial class DateControl : System.Web.UI.UserControl
{
string dateformat;
public string Dateformat
{
get { return dateformat;}
set { dateformat = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
PageLoad();
lnlbtnChangeDate.Visible = false;
ddlDateFormat.Visible = false;
Calendar.Visible = false;
}
lblError.Visible = false;
}
public void PageLoad()
{
if (txtBoxDate.Text != "")
{
Calendar.Visible = false;
}
CultureInfo ci = new CultureInfo("fr-fr");
string[] format = ci.DateTimeFormat.GetAllDateTimePatterns();
foreach (string i in format)
{
ddlDateFormat.Items.Add(i);
}
}
protected void lnkbtnPickDate_Click(object sender, EventArgs e)
{
Calendar.Visible = true;
lnlbtnChangeDate.Visible = true;
ddlDateFormat.Visible = false;
}
public void Calendar_SelectionChanged1(object sender, EventArgs e)
{
txtBoxDate.Text = Calendar.SelectedDate.ToShortDateString();
}
protected void ddlDateFormat_SelectedIndexChanged(object sender, EventArgs e)
{
txtBoxDate.Text = Calendar.SelectedDate.ToString(ddlDateFormat.SelectedValue.ToString());
}
protected void lnlbtnChangeDate_Click(object sender, EventArgs e)
{
Calendar.Visible = false;
if (txtBoxDate.Text == "")
{
lblError.Visible = true;
}
else
{
lblError.Visible = false;
lnlbtnChangeDate.Visible = true;
ddlDateFormat.Visible = true;
}
}
protected void lnkbtnClear_Click(object sender, EventArgs e)
{
txtBoxDate.Text = "";
Calendar.Visible = false;
lnlbtnChangeDate.Visible = false;
ddlDateFormat.Visible = false;
lblError.Visible = false;
}
i said that i want set properties for my user control and create events for that.... plz help me
Not sure I get it right at the question is not very clear, but anyway :
You could just create Properties for you user controls, and assign Enums to them
public enum My_UserControl_DateFormats
{
YYYYMMDD = 1,
YYYYMMDDHH = 2,
YYYYMMDDHHmmSS = 3
}
And in the setter code of your properties handle the logic to assign the Date Format (For Example) according to the enum value (using switch/case)
It's one among many possibilities.