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}.";
}
Related
I have declared a variable globally and it is getting its value from page load function but the variable is not returning the value correctly in the button clicked function.
string id = "1";
protected void Page_Load(object sender, EventArgs e)
{
id = "3";
}
protected void Button1_Click(object sender, EventArgs e)
{
label.text = id;
}
Output
label.text = "1"
why is it so?
well when you click postback runs and assigns value to 3, so you will get only 3 unless you do the page load assignment when it is not postback
string id = "1";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
id = "3";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
label.text = id;
}
I am using Asp.net(C#), and SQL Server. In web application I want 5 digit Invoice number in text box, and after clicking on button the gridviews data to be saved in database, and then invoice number in the text box should be increment by one...and so on. I used this code =>
protected void Page_Load(object sender, EventArgs e)
{
double ID = 00001;
txtinvoiceno.Text = Convert.ToString(ID);
and
protected void btnsavef1_Click(object sender, EventArgs e)
{
ID++;
var no = Convert.ToInt32(ID);
txtinvoiceno.Text = Convert.ToString(no);
}
but it shows in the output only single digit 1, and increment it only once time i.e.2, and further increment is not working.
Anyone have any idea on this??
Thanks & Regards,
I doubt this will even compile, as within btnsavef1_Click the variable ID is not defined. You probably want ID to be an instance-variable:
class MyClass {
private int ID = 0;
protected void Page_Load(object sender, EventArgs e)
{
txtinvoiceno.Text = this.ID.ToString("D5");
}
protected void btnsavef1_Click(object sender, EventArgs e)
{
this.ID++;
txtinvoiceno.Text = this.ID.ToString("D5");
}
}
Furthermore you won´t actually store the formatted number. Simply store the number as integer and do the formatting within your events-code using ToString and format-specifiers.
Try this :
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
int ID = 1;
txtinvoiceno.Text = ID.ToString("D5");
}
}
protected void btnsavef1_Click(object sender, EventArgs e)
{
int ID = Convert.ToInt16(txtinvoiceno.Text );
ID++;
txtinvoiceno.Text = ID.ToString("D5");
}
}
You´re looking for formatting, which is very easy in your case:
//DONE: int, not double - do you want to deal with round-up errors?
//DONE: ID should be a field, not a local variable
private int ID = 0;
protected void Page_Load(object sender, EventArgs e)
{
// whenever you want 5 digits - just put 5 zeroes when formatting
txtinvoiceno.Text = ID.ToString("00000");
...
}
protected void btnsavef1_Click(object sender, EventArgs e)
{
ID += 1;
// once again: want 5 digits - put 5 zeroes when formatting
txtinvoiceno.Text = ID.ToString("00000");
}
A better choice, IMHO, is to convert ID into property and hide formatting there:
private int m_ID;
public int ID {
get {
return m_ID;
}
set {
m_ID = value;
txtinvoiceno.Text = m_ID.ToString("00000");
}
}
...
protected void Page_Load(object sender, EventArgs e) {
// Just assign
ID = 0;
...
}
protected void btnsavef1_Click(object sender, EventArgs e) {
// Just increment
ID += 1;
}
Try this :
public partial class Form2 : Form
{
private double ID=0;
public Form2()
{
InitializeComponent();
}
protected void Page_Load(object sender, EventArgs e)
{
double ID = 00001;
txtinvoiceno.Text = Strings.Format(ID, "000000")
}
protected void btnsavef1_Click(object sender, EventArgs e)
{
ID++;
var no = Convert.ToInt32(ID);
txtinvoiceno.Text = Strings.Format(no, "000000")
}
}
you need to format only result number after increment.
protected void btnsavef1_Click(object sender, EventArgs e)
{
ID++;
var no = Convert.ToInt32(ID);
txtinvoiceno.Text = no.ToString().PadLeft(5, '0');
}
if ID=7
your result will be after Increment
will be 00008
I have a array which I wan't to fill with a textbox, like the javascript .push() method.
Here is my code so far:
namespace Assigment9
{
public partial class Default : System.Web.UI.Page
{
double[] numbers = new double[5];
protected void Page_Load(object sender, EventArgs e)
{
}
protected void addButton_Click(object sender, EventArgs e)
{
double number = Convert.ToDouble(numberTB.Text);
}
}
You need to add the numbers to the array of numbers you declared
double[] numbers = new double[5];
Right now you are just declaring a new variable in addButton_Click called number and not doing anything with it.
It might be easier to use a list of numbers. I.E
List<double> numbers = new List<double>();
Then in addButton_Click just add the number
numbers.Add(mynumber);
You have declared an array of length 5 in the class this means you will need to declare an index variable and do bounds checking to make sure after the addButton is click that the array isnt full. I.E once the user clicks the button more than 5 times. Using the list avoids that effort.
Also you will have an exception in the addButton_Click handler if the user types in a non number value into the text box. You should also look to change that to something like double.TryParse.
public partial class Default : System.Web.UI.Page
{
public List<double> numbers
{
get
{
var list = ViewState["mylist"];
if (list == null) ViewState["mylist"] = new List<double>();
return ViewState["mylist"] as List<double>;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void addButton_Click(object sender, EventArgs e)
{
string value;
double number;
value = numberTB.Text;
if (Double.TryParse(value, out number)) numbers.Add(number);
// you should display some sort of message if the value isnt a number...
}
}
Since this is asp.net web forms you also need to stick the member variable in ViewState or Session otherwise the list or array / whatever will always be empty as web forms doesn't automatically persist member variable values for you.
I would go like this:
public partial class Default : System.Web.UI.Page
{
Collection<double> numbers = new Collection<double>();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void addButton_Click(object sender, EventArgs e)
{
try
{
double number = Convert.ToDouble(numberTB.Text);
numbers.Add(number);
}
catch (FormatException) {
Console.WriteLine("Unable to convert '{0}' to a Double.", number);
}
catch (OverflowException) {
Console.WriteLine("'{0}' is outside the range of a Double.", number);
}
}
}
I know there are lots of way to get the same output .it is also one of them.
According to Your Comment
I know, but I want to be able to add something to numbers[0] and the second time i click the button it should add a number to numbers[1] etc
Here is Solution
namespace Assigment9
{
public partial class Default : System.Web.UI.Page
{
double[] numbers = new double[5];
int counter=0; // declare a global variable which will count the number of button clicks
protected void Page_Load(object sender, EventArgs e)
{
}
protected void addButton_Click(object sender, EventArgs e)
{
if(counter <5)
{
numbers[counter] = Convert.ToDouble(numberTB.Text);
counter ++;
}
}
}
Why would you like to use C# to load List from server side TextBox component. I would recommend to use Javascript for that.
But, if you explicitilly want to load list from c# code with TextBox you should use Session for instance because when you click on the button the page is making post back so the initialized list gets reseted.
Here's the result code:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
List<double> numbers = new List<double>();
Session["numbers"] = numbers;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Session["numbers"] != null)
{
List<double> numbersResult = Session["numbers"] as List<double>;
double number = Convert.ToDouble(TextBox1.Text);
numbersResult.Add(number);
Session["numbers"] = numbersResult;
}
}
I have a disabled text box thats' value only increments by one once a button is clicked, the problem is that it goes from 1 to 2 and thats it. I want it to increment everytime i push the button.
namespace StudentSurveySystem
{
public partial class AddQuestions : System.Web.UI.Page
{
int num = 1;
protected void Page_Load(object sender, EventArgs e)
{
QnoTextBox.Text = num.ToString();
}
protected void ASPxButton1_Click(object sender, EventArgs e)
{
num += 1;
QnoTextBox.Text = num.ToString();
}
}
}
Postback intializes the variable num to 1 again and you do not get the expected increamented result, you better you textbox value and store the value in ViewState.
protected void ASPxButton1_Click(object sender, EventArgs e)
{
num = int.Parse(QnoTextBox.Text);
num++;
QnoTextBox.Text = num.ToString();
}
Using ViewState
public partial class AddQuestions : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
ViewState["Num"] = "1";
}
protected void ASPxButton1_Click(object sender, EventArgs e)
{
QnoTextBox.Text = ViewState["Num"].ToString();
int num = int.Parse(ViewState["Num"].ToString());
ViewState["Num"] = num++;
}
}
I have a website in c#, in the first page I have some listbox, I need that
the last user's choice goes to a label in other page, how can I do that?
In my code if
the user chooses a value a button is visible, and in the click event of that button
redirect to to another page, but I need that value in a label in the page2
if (ddlFunciones.SelectedValue.Equals("15"))
{
lblAgregarNuevoServicio.Visible = true;
//lblIdFuncion.Visible = true;
lblDescripcion.Visible = true;
//txtId_funcion.Visible = true;
txtDescripcionFuncion.Visible = true;
btnAgregarNuevaFuncion.Visible = true;
}
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void btnVerCargos_Click(object sender, EventArgs e)
{
if (btnVerCargos.Enabled)
{
ListBoxCargo.Visible = true;
}
else
{
ListBoxCargo.Visible = false;
}
}
protected void ListBoxCargo_SelectedIndexChanged(object sender, EventArgs e)
{
}
If this is in Asp.Net you can pass information between pages in a number of ways.
You can use the Session object
protected void ListBoxCargo_SelectedIndexChanged(object sender, EventArgs e)
{
Session["MyVar"] = ListBoxCargo.SelectedValue;
}
and in your other page
object value;
if (Session["MyVar"] != null)
{
value = Session["MyVar"]
}
OR
By passing them in the QueryString see Passing-variables-between-pages-using-QueryString
And using Request.QueryString["MyVar"]
and of course there are more, please explain what exactly are you trying to do...
Edit: Based on OPs comments:
In page1:
protected void Button1_Click(object sender, EventArgs e)
{
Session["Page1Value"] = ListBox3.SelectedItem.Text;
//Response.Redirect("~/Page2.aspx");
}
In Page2:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Page1Value"] != null)
{
Label1.Text = Session["Page1Value"].ToString();
}
}
Before you redirect the user to another page, store the selected value in the user's session.
protected void Button1_Click(object sender, EventArgs e)
{
Session["userSelectedValue"] = ListBox1.SelectedValue;
Response.Redirect("OtherPage.aspx");
}
On the other page just extract the selected value from the session.
For example:
protected void Page_Load(object sender, EventArgs e)
{
var selectedValue = Session["userSelectedValue"];
}
More than enough examples of working with session variables available on the interwebs.
I suggest you read up on ASP.NET Session State.