C#: Value not persisting in postback - c#

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class expt2 : System.Web.UI.Page
{
double result ;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
result = 0.0;
protected void Chkbxbd_CheckedChanged(object sender, EventArgs e)
{
if (Chkbxbd.Checked)
{
txtbxttl.Text = "" + 10000;
result += double.Parse(txtbxttl.Text);
}
else
result = result - 10000;
}
protected void Chkbxsfa_CheckedChanged(object sender, EventArgs e)
{
if (Chkbxsfa.Checked)
{
txtbxttl.Text = "" + 15000;
result += double.Parse(txtbxttl.Text);
}
else
result = result - 15000;
}
protected void btnttl_Click(object sender, EventArgs e)
{
txtbxttl.Text = "" + result;
}
}
In this code the individual value for checkbox is ok but when the total is made it becomes 0.
Please help me to fix it.

The "result" value is not persisted through postbacks. Either recalculate it always when you need the final result or store it in the viewstate.

result variable will not be preerved in numereous post backs because the nature of web application is state less so tore the result in a ViewState or Session variable as shown below.
public partial class expt2 : System.Web.UI.Page
{
double result ;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
Session["result"] = 0.0;
}
protected void Chkbxbd_CheckedChanged(object sender, EventArgs e)
{
if (Chkbxbd.Checked)
{
txtbxttl.Text = "" + 10000;
result = double.Parse(Session["result"].ToString());
result += double.Parse(txtbxttl.Text);
Session["result"] = result;
}
else
{
result = double.Parse(Session["result"].ToString());
result = result - 10000;
Session["result"]= result;
}
}
protected void Chkbxsfa_CheckedChanged(object sender, EventArgs e)
{
if (Chkbxsfa.Checked)
{
txtbxttl.Text = "" + 15000;
result = double.Parse(Session["result"].ToString());
result += double.Parse(txtbxttl.Text);
Session["result"] = result;
}
else
{
result = double.Parse(Session["result"].ToString());
result = result - 15000;
Session["result"] = result;
}
}
protected void btnttl_Click(object sender, EventArgs e)
{
txtbxttl.Text = "" + Session["result"].ToString();
}
}

Related

How to change textbox text automatically when other textbox text changes?

I have these textboxes named bags,rate,quantity,packing size and amount what i want to do is that when user enters bags and rate and packing size the quantity textbox should automatically shows the corresponding quantity and amount but in my case when i click on calculate button then it calculates and show the quantity and amount i have tried using textchanged event but it does not do the job?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Login
{
public partial class Sale : Form
{
SaleCalci sale;
SaleBillheader SaleHeaderModel = new SaleBillheader();
tbl_SaleBillDetails SaleDetailModel = new tbl_SaleBillDetails();
public Sale()
{
InitializeComponent();
}
private void Cancelbtn_Click(object sender, EventArgs e)
{
clear();
}
private void clear()
{
txtBillNo.Text = txtDesc.Text = "";
txtBags.Text = txtQty.Text = txtRate.Text = txtAmt.Text = "0.00";
if(txtQty.Text !=null && txtAmt.Text !=null )
{
txtQty.Text = "0.00";
txtAmt.Text = "0.00";
}
Savebtn.Text = "Save";
SaleHeaderModel.SaleBillHeaderId = 0;
SaleDetailModel.SaleBill_Id = 0;
}
private void Exitbtn_Click(object sender, EventArgs e)
{
var result = MessageBox.Show("Are you sure you want to close this form ?", "Confirm", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{ this.Close(); }
}
private void Sale_Load(object sender, EventArgs e)
{
ItemCombo();
PartyCombo();
PackingSizeCombo();
// clear();
}
private void ItemCombo()
{
UserDataEntities db = new UserDataEntities();
Itembox.DataSource = db.tbl_ItemId.ToList();
Itembox.ValueMember = "ItemId";
Itembox.DisplayMember = "ItemName";
}
private void PartyCombo()
{
UserDataEntities db = new UserDataEntities();
PartyBox.DataSource = db.tbl_Parties.ToList();
PartyBox.ValueMember = "Id";
PartyBox.DisplayMember = "PartyName";
}
private void PackingSizeCombo()
{
UserDataEntities db = new UserDataEntities();
PackingBox.DataSource = db.PackingSizes.ToList();
PackingBox.ValueMember = "PackingSizeId";
PackingBox.DisplayMember = "PackingSize1";
}
private void Savebtn_Click(object sender, EventArgs e)
{
CalculateAmount();
DisplayAmt();
}
private void CalculateAmount()
{
int bags = 0;
decimal rate = 0;
int pksize = 0;
bags = Convert.ToInt32(txtBags.Text);
rate = Convert.ToDecimal(txtRate.Text);
pksize = Convert.ToInt32(PackingBox.Text);
sale = new SaleCalci(bags,rate, pksize);
//sale.Bags = Convert.ToInt32(txtBags.Text);
//sale.Rate = Convert.ToDecimal(txtRate.Text);
//SaleDetailModel.Bags = int.Parse(txtBags.Text.Trim());
//SaleDetailModel.Qty = Convert.ToDecimal(txtQty.Text.Trim());
//SaleDetailModel.Rate = Convert.ToDecimal(txtRate.Text.Trim());
// SaleDetailModel.Amount = amount;
}
private void txtAmt_TextChanged(object sender, EventArgs e)
{
// txtAmt.Text = sale.CalucalteAmt.ToString();
}
private void Sale_Click(object sender, EventArgs e)
{
if ((txtBags.Text == "0.00") && (txtQty.Text == "0.00")&&(txtRate.Text == "0.00")&& (txtAmt.Text =="0.00"))
{
txtAmt.Clear();
txtBags.Clear();
txtQty.Clear();
txtRate.Clear();
}
}
private void txtQty_TextChanged(object sender, EventArgs e)
{
DisplayAmt();
}
private void txtBags_TextChanged(object sender, EventArgs e)
{
// sale.Bags = Convert.ToInt32(txtBags.Text);
// DisplayAmt();
}
private void PackingBox_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void txtRate_TextChanged(object sender, EventArgs e)
{
// DisplayAmt();
}
private void DisplayAmt()
{
decimal _amt = sale.CalucalteAmt;
txtQty.Text = sale.CalculateQty().ToString();
txtAmt.Text = _amt.ToString();
}
}
}
Normally "TextChanged" event fires autamatically if text value changes.
So here the problem is i think about your other "partial class" in which there has to exist eventhandler work. Something like:
txtBags.TextChanged += new EventHandler(txtBags_TextChanged);
Please check your other partial class if this staement exist.
This eventhandler sometimes disappears from project if you move your gui elements or for some other causes...
You can readd this statement manually.
By the way if you have not experience with the other partial class then you can try to remove these textboxes and re-add them then your problem will autamatically solves.
You need to call DisplayAmt in the TextChanged event of txtBags , txtRate and Size. In the code above, call to DisplayAmt is commented out. Instead, you are calling DisplayAmt in the TextChanged event of txtQty.
You should be, instead doing.
private void txtAmt_TextChanged(object sender, EventArgs e)
{
DisplayAmt();
}
private void txtRate_TextChanged(object sender, EventArgs e)
{
DisplayAmt();
}
Similarly, you need to add Changed event for Text Control for Size. The txtQty is updated by the DisplayAmt() method. So you don't necessarily need it, unless for reasons that are not specified in OP.

Saving Radio Button State

I want to save radio button state and select the radio button again on reloading the page. I have written the following code but it is not working:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Question_1 : System.Web.UI.Page
{
public int index;
public bool flag = false;
protected void Page_Load(object sender, EventArgs e)
{
if(flag)
{
index = (int)Session["index"];
if (index == 5)
{
totallyagree.Checked = true;
}
else if (index == 4)
{
agree.Checked = true;
}
}
}
protected void next_Click(object sender, EventArgs e)
{
flag=true;
if (totallyagree.Checked)
{
Session["index"] = 5;
}
else if (agree.Checked)
{
Session["index"] = 4;
}
Response.Redirect("Question 2.aspx");
}
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
//Session["index"] = RadioButtonList1.SelectedIndex;
}
}
Please help me with this issue.
did you try IsPostBack ?
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
index = (int)Session["index"];
if (index == 5)
{
totallyagree.Checked = true;
}
else if (index == 4)
{
agree.Checked = true;
}
}
}

imgCheck.ImageUrl = "/images/Blank.jpg"; wont work

Title explains it all. I am using this code at the top. It works. But you will see my comments at the bottom where it does not do anything. Everything else in the section works, just not that last line.
for testing, I created a separate button with the same line, it worked, but In the text changed handler for that specific text box, it just doesn't do anything.
thanks for the help.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Visitor_Tracking
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//if (double.Pharse txtboxVisitorCode.TextChanged += )
{
txtboxVisitorCode.Focus();
imgCheck.ImageUrl = "/images/Blank.jpg";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
imgCheck.ImageUrl = "/images/GreenCheck.jpg";
}
protected void txtboxVisitorCode_TextChanged(object sender, EventArgs e)
{
if (txtboxVisitorCode.Text == "1234")
{
imgCheck.ImageUrl = "/images/GreenCheck.jpg";
lblPlate.Visible = true;
txtboxPlate.Visible = true;
btnPlate.Visible = true;
txtboxPlate.Focus();
}
else
{
imgCheck.ImageUrl = "/images/RedX.jpg";
txtboxVisitorCode.Text = "";
}
}
protected void txtboxPlate_TextChanged(object sender, EventArgs e)
{
lblPlate.Visible = false;
txtboxPlate.Visible = false;
txtboxPlate.Text = "";
txtboxVisitorCode.Text = "";
btnPlate.Visible = false;
btnPlate.Visible = false;
//
//
//
// this line does nothing
imgCheck.ImageUrl = "/images/Blank.jpg";
//
//
}
}
}

"System.UnauthorizedAccessException" error when opening second serial port

i Need to open a second serialPort in my Visual C# program to read data from my arduino.
it already worked fine, but in the case you see below it does not work..
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using CommandsPD4I;
namespace CSharpExample
{
public partial class CSharpExample : Form
{
public ComMotorCommands motor1;
public CSharpExample()
{
InitializeComponent();
motor1 = new ComMotorCommands();
motor1.SetSteps(Convert.ToInt32(numericSchritte.Value));
}
SerialPort arduino;
delegate void InvokeLB(string Data);
InvokeLB lbRecievedDelegate;
int xPos = 0;
private void StartBtn_Click(object sender, EventArgs e)
{
// Set comm settings for motor 1
motor1.SelectedPort = ComPortBox1.Text;
motor1.Baudrate = Convert.ToInt32(BaudrateBox1.Text);
// Set motor address
motor1.MotorAddresse = Convert.ToInt32(Motor1ID.Value);
// Set relative positioning mode
motor1.SetPositionType(1);
// Start travel profile
if (motor1.ErrorFlag)
{
StatusLabel1.Text = "Status 1: " + motor1.ErrorMessageString;
}
else
{
StatusLabel1.Text = "Status 1: OK";
}
}
private void StopBtn_Click(object sender, EventArgs e)
{
// Stop travel profile
motor1.StopTravelProfile();
}
private void timer1_Tick(object sender, EventArgs e)
{
lblPosition.Text = Convert.ToString(motor1.GetPosition());
lblStatus.Text = motor1.ErrorMessageString;
// this.chart1.Series["Kraft"].Points.AddXY(xPos, Convert.ToDouble(lblKraft.Text));
// xPos++;**strong text**
}
private void btnHoch_Click(object sender, EventArgs e)
{
motor1.SetDirection(0);
motor1.SetPositionType(1);
motor1.StartTravelProfile();
}
private void btnRunter_Click(object sender, EventArgs e)
{
motor1.SetDirection(1);
motor1.SetPositionType(1);
motor1.StartTravelProfile();
}
private void numericSchritte_ValueChanged(object sender, EventArgs e)
{
motor1.SetSteps(Convert.ToInt32(numericSchritte.Value));
}
private void numericGeschwindigkeit_ValueChanged(object sender, EventArgs e)
{
motor1.SetMaxFrequency(Convert.ToInt32(numericGeschwindigkeit.Value));
}
private void btnDiagramm_Click(object sender, EventArgs e)
{
if (timer1.Enabled)
{
timer1.Stop();
}
else
{
timer1.Start();
}
}
private void btnResetDiagramm_Click(object sender, EventArgs e)
{
this.chart1.Series["Kraft"].Points.Clear();
xPos = 0;
}
private void arduino_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string RecievedLine = " ";
while (RecievedLine != "")
{
RecievedLine = arduino.ReadLine();
lblKraft.Invoke(lbRecievedDelegate, new object[] { RecievedLine });
}
}
void Invokelabel1(string Data)
{
label1.Text = Data;
this.chart1.Series["Kraft"].Points.AddXY(xPos, Convert.ToDouble(lblKraft.Text));
xPos++;
}
private void btnArduino_Click(object sender, EventArgs e)
{
//Hier erstellen wir unseren Serialport und legen die Einstellungen fest
arduino = new SerialPort("COM7", 9600);
if (!arduino.IsOpen)
{
arduino.Open();
if (arduino.IsOpen)
{
lblArduino.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(200)))), ((int)(((byte)(0)))));
lblArduino.Text = "Verbunden mit " + arduino.PortName;
}
}
lbRecievedDelegate = new InvokeLB(Invokelabel1);
arduino.DataReceived += new SerialDataReceivedEventHandler(arduino_DataReceived); //DataRecieved Event abonnieren
}
}
}
When i leave out this:
motor1.SelectedPort = ComPortBox1.Text;
motor1.Baudrate = Convert.ToInt32(BaudrateBox1.Text);
then it works..
I hope you can help :)

adding a counter class to winform

I have a project that wants
A method that returns the current count.
A Constructor that sets the count to zero.
I have the first few down but need help with the return count to 0 and then the constructor. I need to do this by adding a counter class but I'm confused about the way to add it.
Can some one help me out?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Project10TC
{
public partial class Form1 : Form
{
int zero = 0;
int i = 1;
public Form1()
{
InitializeComponent();
}
private EventHandler myCounter;
// end of Form class
private class myCounter()
{
myCounter = new myCounter( );
}
private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
{
this.Close();
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Teancum Clark\nCS 1400\n Project 10");
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = (++i).ToString();
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = (--i).ToString();
}
private void button3_Click(object sender, EventArgs e)
{
textBox1.Text = (zero).ToString();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
public class Counter
{
public int Value { get; private set; }
public void Increment()
{
Value = Value + 1;
}
public void Decrement()
{
if (Value > 0) Value = Value - 1;
}
public Counter()
{
Value = 0;
}
}

Categories

Resources