Why does my variable lose its value? - c#

From the selectedindexchanged event, my variable has a value, but when it reaches the btn_click() event, the variable no longer has a value. Why is that?
public partial class TestingDatapass
{
private string item = null;
private string itemprice = null;
private int totalprice = 0;
protected void item_selectedindexchanged(object sender, EventArgs e)
{
//Both have a value here
item = item.SelectedValue;
itemprice = item.SelectedValue.Text;
}
protected void btn_click(object sender, EventArgs e)
{
//no value here
totalprice = Convert.ToInt32(itemprice)*Convert.ToInt32(item);
MessageBox.Show(totalprice);
}
}
EDIT
And to answer the ? posed in comments, the order of occurrence is the selectedindexchange THEN the btn_click()
EDIT REGARDING View State
So then would this be a proper way to set up what I am trying to achieve?
public partial class TestingDatapass
{
private int totalprice = 0;
protected void item_selectedindexchanged(object sender, EventArgs e)
{
ViewState["item"] = item.SelectedValue;
ViewState["itemprice"] = item.SelectedValue.Text;
}
protected void btn_click(object sender, EventArgs e)
{
totalprice = Convert.ToInt32(ViewState["item"])*Convert.ToInt32(ViewState["itemprice"]);
}
}

When a page is requested, ASP.NET creates an instance of TestingDatapass class and initialize itemprice,totalprice etc. fields. Now when you change your dropdown from client (which I assume looking at your item_selectedindexchanged method), Postback happens and it assign values you have mentioned in item_selectedindexchanged. Finally it destroys the instance, generates the html and sends it back to browser.
Now, when you press the button in your page then a new instance is created, your fields are re-initialized and you don't see the changed values in btn_click. This is how it works.
Thus if you want to preserve any data across postback, Consider using any State Management technique like ViewState, HiddenField etc.
Also, as a side note, MessageBox.Show is not available in ASP.NET.
Update:
I answered in the context of why it is not retaining the value in button click event, there are many ways to do it. But to answer your question, I don't see any reason to store the values in item_selectedindexchanged event as you are not doing anything there. You can directly access the dropdown selected values in button click handler like this:-
protected void btn_click(object sender, EventArgs e)
{
totalprice = Convert.ToInt32(item.SelectedValue) *
Convert.ToInt32(item.SelectedItem.Text);
}
Also, please note it's item.SelectedItem.Text and not SelectedValue.Text.

Related

How can i add seconds in a date time picker in c#?

I want that when you press a button, it adds 30 seconds to the date timer picker. but what happens to me is that they do not add up.
This is my code:
public partial class Form1 : Form
{
double seg;
public void Form1_Load(object sender, EventArgs e)
{
this.dateTimePicker1.Value = this.dateTimePicker1.Value.AddSeconds(seg);
}
private void s30_Click(object sender, EventArgs e)
{
seg = 30;
}
}
Update the control's value in the click event:
private void s30_Click(object sender, EventArgs e)
{
seg = 30;
this.dateTimePicker1.Value = this.dateTimePicker1.Value.AddSeconds(seg);
}
The Form_Load event only happens when the form is first loaded. (Note that this is specific to Windows Forms. In Web Forms you'll need to take this a step further and persist the value somewhere, because every post-back would load a new instance of the form and the value would start over.)
Of course, since seg never changes to anything but its hard-coded value, you don't really need it. Just increment the seconds by that hard-coded value:
private void s30_Click(object sender, EventArgs e)
{
this.dateTimePicker1.Value = this.dateTimePicker1.Value.AddSeconds(30);
}
Then you can remove the seg variable from your code entirely.

Session variable + WebMethod variable value not updating

I have a web app with a dropdown list. When a new index is selected I have to storing the value to a session variable, which is created on Session_Start event.
protected void Session_Start(object sender, EventArgs e)
{
Session.Add("testValue", "test");
}
On selectedindex changed event i'm setting the new value like this
Session["testValue"] = DropDownList.SelectedItem.Text;
I have a web service where I retrieve the value of the session variable like this:
[WebMethod(EnableSession = true)]
public string getValue()
{
var testVal = Session["testValue"].ToString();
return testVal.ToString();
}
From a console app I connect to the web service and retrieve the value returned by getValue(), however the initial value is always being returned. any idea please?
The issue is because when the console app is run it seems that a new session is created. Using Application state using Application.Set and Application.Get solved the issue. Hopefully i will not have issues when the system will be used by multiple users.
Check whether the values of the items in your dropdown list are different.This is essential for your selected index changed event to be fired.
Here the values are not changed, You didn't change the values. So nothing expected
public string getValue()
{
var testVal = Session["testValue"].ToString();
return testVal.ToString();
}
The mistake is probably in dropdownlist
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Session["testValue] = dropdownlist1.SelectedItem.text;
}
}
And,
protected void dropdownlist1_SelectedIndexChanged(object sender, EventArgs e)
{
Session["testvalue"] = dropdownlist1.SelectedItem.text;
}
Also try with
System.Web.HttpContext.Current.Session["testvalue"]
in both parts

In the WinForms DevExpress XtraWizard control, how can one hide the back button?

I know that if I set the WizardStyle of an XtraWizard control to WizardAero, it will remove or hide the back button from the first page instead of simply disabling it, as can be seen here. I want the same behaviour, but I want to keep the WizardStyle as Wizard97.
Is this possible, and if so, how?
One way to do this would be to use the CustomizeCommandButtons event on the WizardControl.
private void wizardControl1_CustomizeCommandButtons(object sender, CustomizeCommandButtonsEventArgs e)
{
e.PrevButton.Visible = false;
}
If you only want to hide it on the first page
private void wizardControl1_CustomizeCommandButtons(object sender, CustomizeCommandButtonsEventArgs e)
{
if(wizardControl1.SelectedPageIndex == 0)
e.PrevButton.Visible = false;
}
It seems like it will reset the visibility each time (so you don't need to toggle it back on). Anyway, I think this is what you're looking for.
http://documentation.devexpress.com/#WindowsForms/DevExpressXtraWizardWizardControl_CustomizeCommandButtonstopic
You can also set your own fields to the wizard buttons and then use these anywhere in your code. This will, for example, allow you to hide/disable the "Next" button until all fields page have been completed.
private void NodeConfigurationWizardCustomizeCommandButtons(object sender, CustomizeCommandButtonsEventArgs e)
{
_nextButton = e.NextButton;}
private void GetRowsButtonClick(object sender, EventArgs e)
{
var rowList = ServiceClient.GetAvailableRows();
var rowsReturned = rowList.Count > 0;
_nextButton.Button.Enabled = rowsReturned ;}

Making two boxes equal each other

I am trying to make a text box (UPC_txtBox4) self populate to equal the same value of UPC_txtBox2. The two text boxes are on separate forms but I feel there should be a way to link the two.
If form1 is responsible for navigating to form2, then you can pass the value on the query string from form1 using a URL similar to the following:
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
Response.Redirect(Request.ApplicationPath + "/Form2.aspx?upc=" + UPC_txtBox2.Text, false);
}
}
then in form2 code:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
// Assuming this field is an asp.net textbox and not an HTML input
UPC_txtBox4.Text = Request.QueryString["upc"];
}
}
Alternatively, you could store the value in session state, assuming that you are using sessions.
CORRECTION: Seeing as you are using WebForms, not WinForms as I had assumed, the below is irrelevant. I'll leave it just incase it helps someone else.
You should just create a method on the form that needs to be updated, then pass a reference when of that form to the newly created form.
This won't work if either form is a dialog (as far as I know).
So:
Form that has the textbox that will be directly edited.
private Form formToUpdate;
public void OpenForm(Form _formToUpdate)
{
formToUpdate = _formToUpdate;
txtBlah.TextChanged += new EventHandler(OnTextChanged);
this.Show();
}
private void OnTextChanged(object sender, EventArgs e)
{
formToUpdate.UpdateText(txtBlah.Text);
}
Form that is to be dynamically updated:
delegate void StringParameterDelegate (string value);
public void UpdateText(string textToUpdate)
{
if (InvokeRequired)
{
BeginInvoke(new StringParameterDelegate(UpdateText), new object[]{textToUpdate});
return;
}
// Must be on the UI thread if we've got this far
txtblah2.Text = textToUpdate;
}
Note: this is untested (although it should work), and largely pseudo code, you'll need to tailor it to your solution obviously.

Null Reference exception when accessing property in OnClick

Please help me to figure out what is wrong with this code:
I have ASP.NET page with one button visible.
When user clicks it - it instances MyClass (its implementation is in AppCode directory) and turns invisible (button2 becomes visible).
When I click button2 it raises "Object reference not set to an instance of an object" Exception.
What seems to be the problem?
{
public MyClass noviTest;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
noviTest = new MyClass(TextBox1.Text);
Button1.Visible = false;
Button2.Visible = true;
}
protected void Button2_Click(object sender, EventArgs e)
{
Label1.Text=noviTest.getID; //this is the critical line
}
}
Since on postback the noviTest reference to MyClass is not recreated.
You can add it to the viewstate to keep a reference to it. (Assuming MyClass is serializable).
In Button1_Click:
ViewState("noviTest") = noviTest;
Then in Button2_Click:
var noviTest = ViewState("noviTest");
noviTest is null inside Button2_Click.
Try something like this:
protected void Page_Load(object sender, EventArgs e)
{
noviTest = new MyClass(TextBox1.Text);
}
protected void Button1_Click(object sender, EventArgs e)
{
Button1.Visible = false;
Button2.Visible = true;
}
protected void Button2_Click(object sender, EventArgs e)
{
Label1.Text = noviTest.getID;
}
This will cause noviTest to be instantiated on each page request, regardless of which button was clicked. This may not be the best solution for your particular application (I am unfamiliar with the rest of the logic in this class) but you get the idea.
Each visit to the code-behind is kind of like running the code from scratch, nothing is set up or preserved for you between visits to page.
So when you hit the second button noviTest is not initialised and therefore when you attempt to call .getID to you get a null reference exception.
To deal with this you need to ensure that noviTest is initialised. If you want to have it persisted between visits to the page you need to use some mechanism to either store or recreate the instance. To store it you would (probably) use session. To recreate you would use either session or viewdata to persist a key value that would then allow you to retrieve the object state from storage of some kind.

Categories