Values not retained after postback during a method call - c#

I am currently working on migration of a vb.net desktop application into a web application, in the desktop application the previous developer had declared all the variables once on the
form_load
stdate = VB6.Format(Now, "mmddyyyyhh")
current_month = CInt(Mid(stdate, 1, 2))
current_day = CInt(Mid(stdate, 3, 2))
current_year = CInt(Mid(stdate, 5, 4))
current_hour = CInt(Mid(stdate, 9, 2))
base_year = current_year
this_year = current_year
base_month = current_month
this_month = current_month
txtBaseyear.Text = CStr(base_year)
txtBaseMonth.Text = CStr(base_month)
swyearerror = 0
They were then able to use these variables anywhere in the code and it would retain the values.
my application
protected void Page_Load(object sender, EventArgs e)
{
DateTime now = DateTime.Now;
string format = "MMdyyyyhh";
string stdate = now.ToString(format);
Session["stdate"] = stdate;
int current_month = Convert.ToInt32(now.Month);
Session["currentmonth"] = current_month;
int current_day = Convert.ToInt32(now.Day);
Session["currentday"] = current_day;
int current_year = Convert.ToInt32(now.Year);
Session["currentyear"] = current_year;
int current_hour = Convert.ToInt32(now.Hour);
Session["currenthour"] = current_hour;
int base_year = (int)(Session["currentyear"]);
int this_year = (int)(Session["currentyear"]);
int base_month = (int)(Session["currentmonth"]);
int this_month = (int)(Session["currentmonth"]);
TxtBase.Text = Convert.ToString(base_year);
TxtBase1.Text = Convert.ToString(base_month);
}
Now each time there is a post-back when the text is changed the values are lost and set to zero so I tried storing it in a session but that still doesn't work.
Let me give you a visual of my situation.
1) on the first load everything loads fine.
2) then the users enters an item and hits enter
protected void TxtItem_TextChanged(object sender, EventArgs e)
{
Calc_Rotation();
Calc_Best_Before();
}
now...
public void Calc_Rotation()
{
switch (current_month) becomes 0 suppose to be 4
{
case 1:
rotation_month = "A";
break;
case 2:
rotation_month = "B";
break;
case 3:
rotation_month = "G";
break;
case 4:
rotation_month = "J";
break;
case 5:
rotation_month = "K";
break;
case 6:
rotation_month = "L";
break;
case 7:
rotation_month = "N";
break;
case 8:
rotation_month = "P";
break;
case 9:
rotation_month = "S";
break;
case 10:
rotation_month = "W";
break;
case 11:
rotation_month = "Y";
break;
case 12:
rotation_month = "Z";
break;
}
switch (current_hour) becomes 0 suppose to be the current hour
{
case 0:
case 1:
rotation_batch = 2;
break;
case 2:
case 3:
rotation_batch = 4;
break;
case 4:
case 5:
rotation_batch = 6;
break;
case 6:
case 7:
rotation_batch = 8;
break;
case 8:
case 9:
rotation_batch = 10;
break;
case 10:
case 11:
rotation_batch = 12;
break;
case 12:
case 13:
rotation_batch = 14;
break;
case 14:
case 15:
rotation_batch = 16;
break;
case 16:
case 17:
rotation_batch = 18;
break;
case 18:
case 19:
rotation_batch = 20;
break;
case 20:
case 21:
rotation_batch = 22;
break;
case 22:
case 23:
rotation_batch = 24;
break;
}
}
same goes for the Calc_Best_Before
after I tried the postback solution I am still getting 0 values.

protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
return;
DateTime now = DateTime.Now;
string format = "MMdyyyyhh";
string stdate = now.ToString(format);
Session["stdate"] = stdate;
int current_month = Convert.ToInt32(now.Month);
Session["currentmonth"] = current_month;
int current_day = Convert.ToInt32(now.Day);
Session["currentday"] = current_day;
int current_year = Convert.ToInt32(now.Year);
Session["currentyear"] = current_year;
int current_hour = Convert.ToInt32(now.Hour);
Session["currenthour"] = current_hour;
int base_year = (int)(Session["currentyear"]);
int this_year = (int)(Session["currentyear"]);
int base_month = (int)(Session["currentmonth"]);
int this_month = (int)(Session["currentmonth"]);
TxtBase.Text = Convert.ToString(base_year);
TxtBase1.Text = Convert.ToString(base_month);
}

Put your code inside the below code. If the web page loads for the first time IsPostBack property is 'false' and code inside the if condition will be executed.
if the page loads after a post back IsPostBack turns to 'true' which cause program execution to escape the if condition.
if (!IsPostBack)
{
}

In case you are using Session to store the values, you need to ensure that you are checking the IsPostBack Property. Otherwise, everytime the page postback occurs, you are initializing the values again and thus you loose the state.
Page.IsPostBack property basically signifies whether the Page is accessing the server for the first time or not.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DateTime now = DateTime.Now;
string format = "MMdyyyyhh";
string stdate = now.ToString(format);
Session["stdate"] = stdate;
int current_month = Convert.ToInt32(now.Month);
Session["currentmonth"] = current_month;
int current_day = Convert.ToInt32(now.Day);
Session["currentday"] = current_day;
int current_year = Convert.ToInt32(now.Year);
Session["currentyear"] = current_year;
int current_hour = Convert.ToInt32(now.Hour);
Session["currenthour"] = current_hour;
int base_year = (int)(Session["currentyear"]);
int this_year = (int)(Session["currentyear"]);
int base_month = (int)(Session["currentmonth"]);
int this_month = (int)(Session["currentmonth"]);
TxtBase.Text = Convert.ToString(base_year);
TxtBase1.Text = Convert.ToString(base_month);
}
}
UPDATE 1:
#CodeMan: You need to use the Session to read the value for the current month in the function Calc_Rotation. You are trying to read the value from the variable current_month which is an int and would default to zero.
I would suggest you to use a Property to wrap up the Session Variable and then use the property in the code. Below, i have created a wrapper property CurrentMonth which encapsulates the Read and write operations on Session in the webpage, declared at class scope. Simmilary you can create wrapper properties for other variables as well. After creating the properties, you need to read the property value in the Calc_Rotation function.
private int CurrentMonth {
get {
var monthfromSession = HttpContext.Current.Session["ClassNameSpace.CurrentMonth"];
return monthfromSession!= null ? (int)monthfromSession : 0;
}
set {
HttpContext.Current.Session["ClassNameSpace.CurrentMonth"] = value;
}
}
public void Calc_Rotation()
{
switch (this.CurrentMonth) // it should have correct month value now.
{
case 1:
rotation_month = "A";
break;
case 2:
rotation_month = "B";
break;
case 3:
....
}
}

Related

c# how to refer to current button

I am trying to make a minesweeper game using Windows Application. I would like to use a switch inside a method.
The problem:
public void switcher()
{
switch (x)
{
case 0:
A1.BackgroundImage = Image.FromFile("empty.jpg"); // look at A1
break;
case 1:
A1.BackgroundImage = Image.FromFile("1.jpg");
break;
case 2:
A1.BackgroundImage = Image.FromFile("2.jpg");
break;
case 3:
A1.BackgroundImage = Image.FromFile("3.jpg");
break;
case 4:
A1.BackgroundImage = Image.FromFile("4.jpg");
break;
case 5:
A1.BackgroundImage = Image.FromFile("5.jpg");
break;
case 6:
A1.BackgroundImage = Image.FromFile("6.jpg");
break;
case 7:
A1.BackgroundImage = Image.FromFile("7.jpg");
break;
case 8:
A1.BackgroundImage = Image.FromFile("8.jpg");
break;
}
}
As you can see, each of them says "A1. ....." A1 is my first button's name, but there are many other buttons as well. Is there a way I can refer to the button's properties, such as background image, without having to use its name? It would make programming so much easier.
Here's a simplified part of the button, if it helps:
private void A1_Click(object sender, EventArgs e) // < - I want to refer to this without using A1 name.
{
x = bombcount[0, 0];
switcher();
}
edit: One of the answers worked. I don't know much about these things, but I'll try to learn more about them! Thank you!
You need to refactor this code altogether. Don't rely on private members such as x like that, use method parameters:
private void SetButtonImage(Button button, int number)
{
string imagePath;
if (number == 0)
{
imagePath = "empty.jpg";
}
else
{
imagePath = number + ".jpg";
}
button.BackgroundImage = Image.FromFile(imagePath);
}
Then call it like this:
private void Button_Click(object sender, EventArgs e)
{
var button = sender as Button;
int number = bombcount[0, 0];
SetButtonImage(button, number);
}
Now you can hook up all button click events to that single event handler, and you can remove the x member, and you can remove the switch altogether.
Get a reference in switcher to the button being clicked like this:
private void A1_Click(object sender, EventArgs e)
{
Button myB = (Button) sender;
x = bombcount[0,0];
switcher(myB);
}
private void switcher(Button button)
{
switch (x)
{
case 0:
button.BackgroundImage = Image.FromFile("empty.jpg"); // look at A1
break;
case 1:
button.BackgroundImage = Image.FromFile("1.jpg");
break;
case 2:
button.BackgroundImage = Image.FromFile("2.jpg");
break;
case 3:
button.BackgroundImage = Image.FromFile("3.jpg");
break;
case 4:
button.BackgroundImage = Image.FromFile("4.jpg");
break;
case 5:
button.BackgroundImage = Image.FromFile("5.jpg");
break;
case 6:
button.BackgroundImage = Image.FromFile("6.jpg");
break;
case 7:
button.BackgroundImage = Image.FromFile("7.jpg");
break;
case 8:
button.BackgroundImage = Image.FromFile("8.jpg");
break;
}
}

How to display a variable mantissa length

I have a label on a form that displays a float (_DataFloat) with a variable (_Digits) that sets the number of digits to show to the right of the decimal point. Assuming that _Digits can be any value from 0 through 6, is there a better way of formatting the text other than using a switch statement as below?
switch (_Digits) {
case 0:
label1.Text = _DataFloat.ToString("0");
break;
case 1:
label1.Text = _DataFloat.ToString("0.0");
break;
case 2:
label1.Text = _DataFloat.ToString("0.00");
break;
case 3:
label1.Text = _DataFloat.ToString("0.000");
break;
case 4:
label1.Text = _DataFloat.ToString("0.0000");
break;
case 5:
label1.Text = _DataFloat.ToString("0.00000");
break;
case 6:
label1.Text = _DataFloat.ToString("0.000000");
break;
default:
label1.Text = _DataFloat.ToString("0.00");
break;
}
How about:
var format = String.Format("0.{0}", new string('0', _Digits));
label1.Text = _DataFloat.ToString(format);

c# web service not returning results

I recently "finished" a new project except there is a small problem. Im not getting my results back.
This project utilizes c# web services via a SOAP client along with Request and Response Classes. The project is designed to reserve something, in this demo, it reserves a seat in a cinema. However when the data is passed from the windows form client to the web service, nothing comes back. I recently stopped the project from freezing upon execution of the web method.
This is the method that calls the web service (The method signature is only temporary)
public void derp()
{
var client = new SampleServiceSoapClient();
var req = new GetReservationRequest();
req.row = row;
req.seat = seat;
req.name = textNameRequest.Text;
try
{
client.GetReservation(req);
}
catch (Exception err)
{
MessageBox.Show("Server Unavailable");
}
}
I am running this method on a seperate thread to stop crashing. The output of this method is supposed to come back through a response object and then i assign the values of said object to text boxes on the form. However, the data is lost before it returns.
The web method is as follows
[WebMethod]
public GetReservationResponse GetReservation(GetReservationRequest req)
{
object o = HttpContext.Current.Cache["Reservation"];
if(o == null)
{
o = reservedSeat;
}
else
{
reservedSeat = (bool[,])o;
}
GetReservationResponse resp = new GetReservationResponse();
string rowHolder = "A";
int rowRequest = req.row;
int seatCopy = 0;
bool emptySeat = false;
while (rowRequest < 12)
{
for (int seat = req.seat; seat < 16; seat++)
{
if (reservedSeat[req.row, seat])
{
//Loop back
}
else
{
emptySeat = true;
seatCopy = seat;
break;
}
}
if (reservedSeat[req.row, 15])
{
seatCopy = 0;
break;
}
}
switch (rowRequest)
{
case 1: rowHolder = "A";
break;
case 2: rowHolder = "B";
break;
case 3: rowHolder = "C";
break;
case 4: rowHolder = "D";
break;
case 5: rowHolder = "E";
break;
case 6: rowHolder = "F";
break;
case 7: rowHolder = "G";
break;
case 8: rowHolder = "H";
break;
case 9: rowHolder = "I";
break;
case 10: rowHolder = "J";
break;
case 11: rowHolder = "K";
break;
case 12: rowHolder = "L";
break;
default: rowHolder = "None Specified";
break;
}
int x = 0;
if (!reservedSeat[rowRequest, seatCopy])
{
reservedSeat[rowRequest, seatCopy] = true;
seatCopy++;
//resp.row = rowRequest;
x = seatCopy;
seatCopy--;
if (seatCopy.Equals(15))
{
rowRequest++;
}
}
resp.row = rowHolder;
resp.seat = x;
//row++
return resp;
}
I have no clue why the data is being lost before it comes back but some information would be amazing...
Where in this code rowrequest is incremented? It seems to me, that you have infinite loop here:
while (rowRequest < 12)
{
for (int seat = req.seat; seat < 16; seat++)
{
if (reservedSeat[req.row, seat])
{
//Loop back
}
else
{
emptySeat = true;
seatCopy = seat;
break;
}
}
if (reservedSeat[req.row, 15])
{
seatCopy = 0;
break;
}
}

casting data split to integer

i realize that it does not read inside if (berjaya[23].Equals(70)) as if it was not equal to 70. but when i tried to show berjaya[23] using MessageBox, it do appear 70.
my first guess is casting. i tried int value = (int)(berjaya[23]); and my next plan is try do if(value == 70) but it says string cannot be convert to int.
is there any other way for the (berjaya[23].Equals(70)) be read?
===EDIT===
i should casting the data split by this way:
int.TryParse(berjaya[23], out value1);
then to change the picture, i used this:
if (value1 == 301)
{
Bitmap abc = (Bitmap)System.Drawing.Bitmap.FromFile("C:\\Users\\HDAdmin\\Pictures\\HospitalIcon\\web\\web2\\images\\a3_01.gif");
pictureBox1.Image = abc;
}
Try this, but set the image names
Bitmap abc = (Bitmap)System.Drawing.Bitmap.FromFile("C:\\Users\\HDAdmin\\Pictures\\HospitalIcon\\fafa\\images\\a3_00.gif");
if (berjaya[23].Equals(70))
{
abc = (Bitmap)System.Drawing.Bitmap.FromFile("C:\\Users\\HDAdmin\\Pictures\\HospitalIcon\\fafa\\images\\a3_01.gif");
}
myPicturebox.Image = abc;
You must add first a Empty bitmap.
like:
Bitmap abc;
Or you can assign value for that. Then in if/else you change into:
abc = (Bitmap)System.Drawing.Bitmap.FromFile("C:\\Users\\HDAdmin\\Pictures\\HospitalIcon\\fafa\\images\\a3_01.gif");
Additonal:
Ops, sorry Miss/Mr/Ms (What must I say?) Sara Brown, That will be a much complicated. add this function
public int value(string num){
string a = num.split("");//If this function true?
int res = 0;
for(var b = 0; b<a.Length; b++){
res = res*10;
switch(a[b]){
case "0":
break;
case "1":
res += 1;
break;
case "2":
res += 2;
break;
case "3":
res += 3;
break;
case "4":
res += 4;
break;
case "5":
res += 5;
break;
case "6":
res += 6;
break;
case "7":
res += 7;
break;
case "8":
res += 8;
break;
case "9":
res += 9;
break;
}
}
return res;
}
the add this code
Bitmap abc;
if(value(Berjaya[23])==70){
abc = (Bitmap)System.Drawing.Bitmap.FromFile("C:\\Users\\HDAdmin\\Pictures\\HospitalIcon\\fafa\\images\\a3_01.gif");
}

Populate PieChart based on SQL Server stored procedure

I have the following stored procedure that I have to get data from:
EXECUTE [dbo].[StationHealthStatusSummary2]
#LineId varchar(100), // 5,9,10
#MeasurementDt datetime, //2012/06/06
#Ntotal Int output,
#N0 int output,
#N1 int output,
#N2 int output,
#N3 int output,
#N4 int output,
#N5 int output,
#N6 int output,
#N7 int output,
#N8 int output,
#N9 int output,
#N10 int output,
#N11 int output,
#N12 int output,
#N13 int output,
#N14 int output,
#N15 int output,
#N16 int output
GO
Now I can send parameters to LineID and Measurement date as follows:
SqlConnection sql = new SqlConnection(#"Data Source=(local)\SQLEXPRESS;Initial Catalog=iComs;Persist Security Info=True;User ID=sa;Password=Password);
SqlCommand getData = new SqlCommand("StationHealthStatusSummary2", sql);
SqlDataAdapter da = new SqlDataAdapter(getData);
getData.CommandType = CommandType.StoredProcedure;
getData.Parameters.Add(new SqlParameter("#LineId", Lines));
getData.Parameters.Add(new SqlParameter("#MeasurementDt", date1));
SqlParameter ParamaterNtotal = new SqlParameter();
ParamaterNtotal.ParameterName = "#Ntotal";
ParamaterNtotal.SqlDbType = SqlDbType.Int;
ParamaterNtotal.Direction = ParameterDirection.Output;
getData.Parameters.Add(ParamaterNtotal);
sql.Open();
getData.ExecuteNonQuery();
Now I can get the value of NTotal and assign it to a Teechart (PieSlice),
but how do I get the value for #N0..#N16?
I've got some code that might give you some idea of what I'm trying to accomplish.
int NTotal = int.Parse(getData.Parameters["#Ntotal"].Value.ToString());
if (GetVariantVariableI(getData.Parameters[0].Value) = 0)
{
for (c = 1; c <= 18; c++)
{
Nvl = GetVariantVariableI(getData.Parameters[2+c].Value);
switch(c)
{
case 1:
NTotal = Nvl;
break;
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 20:
cstatus = c-2;
NPieValues[cstatus] = Nvl;
break;
}
string SliceName;
int NUsed;
NUsed = 0;
for(i=0;i<=16;i++)
{
NUsed = NUsed + NPieValues[i];
}
if (NUsed < NTotal)
{
Chart1.Series[0].Add(NTotal - NUsed);
slice1.Title = "Not Connected";
slice1.Add();
slice1.Color = System.Drawing.Color.Silver;
}
if (NUsed > NTotal)
{
NPieValues[7] = NPieValues[7]-(NUsed-NTotal);
}
for (i=0;i<=16;i++)
{
if (NPieValues[i]>0)
{
switch(i)
{
case 0: SliceName ="Green";
break;
case 1: SliceName ="Yellow";
break;
case 2: SliceName ="Orange";
break;
case 3: SliceName ="Red";
break;
case 4: SliceName ="Broken Rail";
break;
case 5: SliceName ="Buckling Rail";
break;
case 6: SliceName ="Maintenance required";
break;
case 7: SliceName ="Station(s) Off";
break;
case 8: SliceName ="Rail Differential kN";
break;
case 9: SliceName ="Left Rail Sensor Faulty";
break;
case 10: SliceName ="Right Rail Sensor Faulty";
break;
case 11: SliceName ="Temperature Rail Sensor Faulty";
break;
case 12: SliceName ="Calibration Required";
break;
case 13: SliceName ="Station Vandalised";
break;
case 14: SliceName ="Station uninstalled";
break;
case 15: SliceName ="Gauges removed for Maintenance";
break;
case 16: SliceName ="No GSM Coverage";
break;
default:
SliceName ="?";
}
switch(i)
{
case 0: clr = "System.Drawing.Color.Green";
break;
case 1:clr = "System.Drawing.Color.Yellow";
break;
case 2:clr = "System.Drawing.Color.Orrange";
break;
case 3:clr = "System.Drawing.Color.Red";
break;
case 4:
case 5:
case 8:clr = "System.Drawing.Color.Purple";
break;
case 6:clr = "System.Drawing.Color.Black";
break;
case 7:clr = "System.Drawing.Color.Gray";
break;;
case 9:clr = "System.Drawing.ColorTranslator.FromHtml('#E0671F')";
break;
case 10:clr = "System.Drawing.ColorTranslator.FromHtml('#BA4EC2')";
break;
case 11:clr = "System.Drawing.ColorTranslator.FromHtml('#FF8000')";
break;
case 12:clr = "System.Drawing.ColorTranslator.FromHtml('#BF4093')";
break;
case 13:clr = "System.Drawing.Color.SkyBlue";
break;
case 14:clr = "System.Drawing.Color.Aqua";
break;
case 15:clr = "System.Drawing.ColorTranslator.FromHtml('#BFBFFF')";
break;
case 16:clr = "System.Drawing.Color.MedGray";
break;
default : clr = "System.Drawing.Color.White";
break;
}
slice1.Add(NPieValues[i],SliceName,clr);
}
}
}
}
}
Now after it got all those values it has to populate the piechart.
Please, any help will be highly appreciated and please tell me if I'm being too vague.
Thanks
You have added #Ntotal as an Output parameter, why didn't you add all the others?
SqlParameter n = new SqlParameter();
n.ParameterName = "#N0";
n.SqlDbType = SqlDbType.Int;
n.Direction = ParameterDirection.Output;
getData.Parameters.Add(n);
Then you can retrieve the output values the same way you do with #Ntotal. Also, you can retrieve the values by name instead of looping through them, if you prefer.
Thanks. I Figured it out...
after i send the parameters as follows:
SqlParameter Paramater0 = new SqlParameter();
Paramater0.ParameterName = "#N0";
Paramater0.SqlDbType = SqlDbType.Int;
Paramater0.Direction = ParameterDirection.Output;
getData.Parameters.Add(Paramater0);
I then get the value and declare it to a var as follows:
int N0 = int.Parse(getData.Parameters["#N0"].Value.ToString());
and finally declare that int to a slice on the chart as follows:
slice1.Add(N0, "Green", System.Drawing.Color.Green);
Thanks for your help #mgnoonan :)

Categories

Resources