how to pass session value from button click to another cs file - c#

I am trying to attempt to perform a calculation on a button click on one asp.net form (invoice.aspx) then pass it to another response (print.aspx) form and insert that value into a label. However when ever I click the submit the value ends up being 0. No errors arise when this happens. Can this be done??
The following code I have is:
print.aspx.cs
public partial class print : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DateTime date = DateTime.Now;
lblDateIssue.Text = " Date Issue:" + date.ToShortDateString();
var dueDate = date.AddDays(14);
lblDueDate.Text = " DueDate:" + dueDate.ToShortDateString();
double subTotal1 = (double)(Session["subTotal1"]);
lblItem1Ttl.Text = subTotal1.ToString();
}
}
invoice.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Session["subTotal1"] = 0.0;
}
public void btnSubmit_Click(object sender, EventArgs e)
{
int qty1 = Int32.Parse(txtQty1.Text);
double price1 = double.Parse(txtPrice1.Text);
Session["subTotal1"] = (double)Session["subTotal1"] + (price1 * qty1);
}
}
Any guidance would be appreciated

So rather than using the action attribute in the invoice.aspx form. I removed that attribute and put in Server.Transfer("print.aspx", true); to post to the response page on the button click event. I have also added the try - catch functions to stop the exception throwing. So thanks #dee-see because it was the life cycle just had to go a slightly different way to get around it. The full solution is below
invoice.aspx.cs:
public partial class invoice : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
Session["subTotal1"] = 0.0;
Session["subTotal2"] = 0.0;
Session["subTotal3"] = 0.0;
}
}
public void btnSubmit_Click(object sender, EventArgs e)
{
try
{
int qty1 = Int32.Parse(txtQty1.Text);
double price1 = double.Parse(txtPrice1.Text);
Session["subTotal1"] = (double)Session["subTotal1"] + (price1 * qty1);
}
catch
{
txtQty1.Text = "";
txtPrice1.Text = "";
}
try
{
int qty2 = Int32.Parse(txtQty2.Text);
double price2 = double.Parse(txtPrice2.Text);
Session["subTotal2"] = (double)Session["subTotal2"] + (price2 * qty2);
}
catch
{
}
try
{
int qty3 = Int32.Parse(txtQty3.Text);
double price3 = double.Parse(txtPrice3.Text);
Session["subTotal3"] = (double)Session["subTotal3"] + (price3 * qty3);
}
catch
{
txtQty3.Text = "";
txtPrice3.Text = "";
}
Server.Transfer("print.aspx", true);
}
}
print.aspx.cs:
public partial class print : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DateTime date = DateTime.Now;
lblDateIssue.Text = " Date Issue:" + date.ToShortDateString();
var dueDate = date.AddDays(14);
lblDueDate.Text = " DueDate:" + dueDate.ToShortDateString();
lblItem1Ttl.Text += "$" + (double)(Session["subTotal1"]);
lblItem2Ttl.Text += "$" + (double)(Session["subTotal2"]);
lblItem3Ttl.Text += "$" + (double)(Session["subTotal3"]);
double total = ((double)(Session["subTotal1"]) + ((double)(Session["subTotal2"])) + (double)(Session["subTotal3"]));
lblTotalAmount.Text += "$" + total;
}
}

Related

Why am I receiving an System.InvalidCastException when I am trying to call my ShowStatement method?

I am able to add accounts of different types through another form to the list statements which I can then add to the list box lstaccounts. However, when I select an account in my list box and press the view statement button I get that exception on the 'lblBank.Text = ShowStatement((IStatement)lstAccounts.SelectedItem);' line... any idea why this could be happening?
public List<IStatement> statements;
private int accountCounter = 0;
private int statementsViewed = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
statements = new List<IStatement>();
}
private void btnView_Click(object sender, EventArgs e)
{
if (lstAccounts.SelectedIndex > -1)
{
lblBank.Text = ShowStatement((IStatement)lstAccounts.SelectedItem);
statementsViewed += 1;
lblTotal.Text = statementsViewed.ToString();
}
}
private string ShowStatement(IStatement item)
{
String msg = "Account Number: " + item.AccountNumber + "\n"
+ "Name: " + item.AccountName + "\n" + item.PrintStatement();
return msg;
}
private void btnAddAccount_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
if(form2.ShowDialog() == DialogResult.OK)
{
if (form2.txtValue.Text == "" && form2.txtMinMonthly.Text == "")
{
BankAccount b = form2.GetBankAccount();
statements.Add(b);
}
else if (form2.txtMinMonthly.Text == "")
{
InsurancePolicy i = form2.GetInsurancePolicy();
statements.Add(i);
}
else
{
PlatinumCurrent p = form2.GetPlatinumCurrent();
statements.Add(p);
}
foreach (IStatement os in statements)
{
lstAccounts.Items.Add(os.ToString());
accountCounter += 1;
}
}
}
The exact error I'm getting is: System.InvalidCastException: 'Unable to cast object of type 'System.String' to type 'TelephoneBanking.IStatement'.'
You added it as .ToString() in your btnAddAccount_Click. Try add the item, not the item.ToString().
private void btnAddAccount_Click(object sender, EventArgs e)
{
...
foreach (IStatement os in statements)
{
lstAccounts.Items.Add(os); // ###### removed os.ToString() ######
accountCounter += 1;
}
...

Cannot modify the result of an unboxing conversion ASP.Net

So basically i need to get a row count of Table1. I have created a session which stores people in Table1, but when i create a Session for my int counter i get an error "Cannot modify the result of an unboxing conversion". And also, I would like to ask, how can i add row number into "issaugotasTekstas" (my people) in Table1?
Tank you for suggestions!
namespace ValidWeb
{
public partial class WebForm1 : System.Web.UI.Page
{
private String issaugotasTekstas;
protected void Page_Load(object sender, EventArgs e)
{
if (DropDownList1.Items.Count == 0)
{
DropDownList1.Items.Add("-");
for (int i = 14; i <= 25; i++)
{
DropDownList1.Items.Add(i.ToString());
}
}
issaugotasTekstas = (string)Session["Registruoti"]; // session for added people
RegistruotasAsmuo(issaugotasTekstas);
int sk = DalyviuSk(Table1);
(int)Session["Dalyviu sk"] = sk; // ERROR HERE
}
protected void Button1_Click(object sender, EventArgs e)
{
string selected = "";
foreach (ListItem item in CheckBoxList1.Items)
{
if (item.Selected)
{
selected += item.ToString() + " | ";
}
}
issaugotasTekstas = /*row number */ TextBox1.Text + " | " + TextBox2.Text + " | " + TextBox3.Text + " | " + DropDownList1.SelectedValue + " | " + selected;
// how can i add row number for each row?
RegistruotasAsmuo(issaugotasTekstas);
Session["Registruoti"] = issaugotasTekstas;
}
private void RegistruotasAsmuo(string tekstas)
{
TableCell cell = new TableCell();
cell.Text = tekstas;
TableRow row = new TableRow();
row.Cells.Add(cell);
Table1.Rows.Add(row);
}
private int DalyviuSk(Table table)
{
return Table1.Rows.Count;
}
protected void Button2_Click(object sender, EventArgs e)
{
Table1.Rows.Clear();
}
}
}

How to fix the drag and drop using dev express in c# after fetching data and setting tag property

enter image description here
namespace Implementer
{
public partial class MainForm : Form
{
#region intit and globals
public MainForm()
{
InitializeComponent();
DevExpress.XtraGrid.Views.Grid.GridView gridView = new DevExpress.XtraGrid.Views.Grid.GridView();
var transactions = new ObservableCollection<Item>();
for (int i = 0; i <= 100; i++)
{
transactions.Add(new Item { Content = "Item " + i });
}
grdTransactions.AllowDrop = true;
grdTransactions.DataSource = transactions;
dgmWf.AddingNewItem += (s, e) => transactions.Remove(e.Item.Tag as Item);
}
Point mouseDownLocation;
GridHitInfo gridHitInfo;
#endregion
#region events
public void Mainform_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'vA_ERP4_ADMINDataSet.SYSTEM_MODULES' table. You can move, or remove it, as needed.
//Project initiation
//Fill drop down for project list
cmbProject.SelectedIndex = 0;
DataAccess dataAccess = new DataAccess(GlobalFunctions.GetConnectionString());
DataTable dtResult = dataAccess.ExecuteQueryDataSet("select MODULE_CODE, MODULE_DESC from SYSTEM_MODULES where module_is_active=1").Tables[0];
cmbProject.DisplayMember = "MODULE_DESC";
cmbProject.ValueMember = "MODULE_CODE";
cmbProject.DataSource = dtResult;
}
private void cmbProject_SelectedIndexChanged(object sender, EventArgs e)
{
lblCurrentProject.Text = cmbProject.Text;
if (cmbProject.Text != null)
{
DataAccess dataAccess = new DataAccess(GlobalFunctions.GetConnectionString());
DataTable dtTransactions = dataAccess.ExecuteQueryDataSet("select sys_trans_id, sys_trans_desc1 from WF_SYSTEM_TRANS where MODULE_CODE= '" + cmbProject.Text + "'").Tables[0];
grdTransactions.DataSource = dtTransactions;
}
}
private void btnSalesInvoice_Click(object sender, EventArgs e)
{
int sysTransId = 1001;
FillTransactionDetails(sysTransId);
}
#endregion
#region drag drop
private void grdTransactions_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left && CanStartDragDrop(e.Location))
{
StartDragDrop();
}
}
private void grdTransactions_MouseDown(object sender, MouseEventArgs e)
{
gridHitInfo = grdVTransactions.CalcHitInfo(e.Location);
mouseDownLocation = e.Location;
}
private void grdTransactions_MouseLeave(object sender, EventArgs e)
{
if (gridHitInfo != null)
gridHitInfo.View.ResetCursor();
gridHitInfo = null;
}
private bool CanStartDragDrop(Point location)
{
return gridHitInfo.InDataRow && (Math.Abs(location.X - mouseDownLocation.X) > 2 || Math.Abs(location.Y - mouseDownLocation.Y) > 2);
}
public void StartDragDrop()
{
var draggedRow = gridHitInfo.View.GetRow(gridHitInfo.RowHandle) as Item;
var tool = new FactoryItemTool(" ", () => " ", diagram => new DiagramShape(BasicShapes.Rectangle) { Content = draggedRow.Content, Tag = draggedRow }, new System.Windows.Size(150, 100), false);
dgmWf.Commands.Execute(DiagramCommandsBase.StartDragToolCommand, tool, null);
}
#endregion
#region function
private void FillTransactionDetails(int systemTransactionId)
{
//Fill document
//Fill steps
DataAccess dataAccess = new DataAccess(GlobalFunctions.GetConnectionString());
DataTable transactionDetails = dataAccess.ExecuteQueryDataSet("SELECT DOC_TYPE_DESC1 FROM WF_SYSTEM_TRANS_DT WHERE SYS_TRANS_ID=1001 and MODULE_CODE= '" + cmbProject.Text + "'").Tables[0];
transactionDetails.Rows.Add();
grdDocuments.DataSource = transactionDetails;
grdDocuments.Columns["Details"].DisplayIndex = 2;
grdDocuments.Columns["Delete"].DisplayIndex = 2;
DataTable transactionSteps = dataAccess.ExecuteQueryDataSet("select WF_STEP_DESC1 from WF_STEPS where wf_id= 10101 and MODULE_CODE= '" + cmbProject.Text + "'").Tables[0];
transactionSteps.Rows.Add();
grdSteps.DataSource = transactionSteps;
}
#endregion
}
public class Item
{
public string Content { get; set; }
}
}
I don't really know where is the mistake and have been looking at it for the past few days and searching for an answer but no luck so I'd be so happy if you could help me out. It was working without the data fetching. but after calling the data it doesn't work. drag it from the grid view and when it reaches the diagram control it would turn into a rectangle with a tag property of it's ID.. With regards to the connection string.. I created a global function to just call it on the main form.

Deleting a label that was duplicated

I have a program where a user fills in a form and hits calculate, then when the user hits summary it will show all the users that have entered in data. When more users enter data, they are simply added to the summary using the same lbl (lblUsers) the only problem I am having is being able to delete the most recent entry into the summary which would be the newest made label.
using System;
using System.Collections;
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 LifeInsurance
{
public partial class frmMain : Form
{
double commissionRate;
double insuranceAmount;
double totalAmount;
int numberOfCustomers;
double totalInsuranceDollars;
double totalCommission;
private void btnClearAll_Click(object sender, EventArgs e)
{
lblUsers.Text = "";
}
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
}
private void btnCalculate_Click(object sender, EventArgs e)
{
try
{
string firstName = txtFirstName.Text;
string lastName = txtLastName.Text;
insuranceAmount = int.Parse(txtInsuranceAmount.Text);
}catch (Exception)
{
MessageBox.Show("You must enter all details");
}
if(insuranceAmount>= 1000)
{
commissionRate = 0.005;
totalAmount = insuranceAmount * 0.005;
}
if (insuranceAmount >= 100000)
{
commissionRate = 0.0010;
totalAmount = insuranceAmount * 0.0010;
}
if (insuranceAmount >= 1000000)
{
commissionRate = 0.0015;
totalAmount = insuranceAmount * 0.0015;
}
totalInsuranceDollars += totalAmount;
totalCommission += commissionRate;
numberOfCustomers += 1;
lblUsers.Text += "Name: "+txtFirstName.Text +" "+ txtLastName.Text+"
"+ "Payout Amount: "+totalAmount+Environment.NewLine;
lblUsers.Text += "Total Policies: " + numberOfCustomers+" " + "Total
Insurance Dollars Earned: " + totalInsuranceDollars+" " + "Total
Commission Earned: " + totalCommission+Environment.NewLine;
}
private void btnSummary_Click(object sender, EventArgs e)
{
lblUsers.Visible = true ;
}
private void btnClear_Click(object sender, EventArgs e)
{
//remove one label
}
}
}
I'm sorry, if I understand correctly you want your Label to show all but the last entry when the user clicks "Summary" is that correct? So in your screenshot it shows 3 entries, but you want only 2 entries to be shown?
If so, see if this helps:
public static void btnSummary_Click(object sender, EventArgs e)
{
string currentText = lblUsers.Text;
int positionOfLastEntry = currentText.LastIndexOf("Name:");
string textWithoutLastEntry = currentText.Substring(0, positionOfLastEntry);
lblUsers.Text = textWithoutLastEntry;
lblUsers.Visible = true;
}

Total Row Count SqlDataSource GridView

So I have a GridView set up to a SqlDataSource. Paging is enabled and I have a drop down menu that changes the number of rows displayed per page. I am able get the total of rows displayed in a single page but I want to show the total number of rows as well. (Like this: "Showing 1 - 25 of 315").
So, my questions are:
1) How do I get the total number of rows for the entire DataSource? (not just GridView) The code I have, OnSelectedData method, does not work and returns a zero.
2) How do I get the numbers to display differently for each page? For example, on the second page it needs to say "Showing 26 - 50 of 315"
Here's my code (C#):
public partial class UserControls_BloombergAllUsersControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
int gridViewTotalRowCount;
protected void onSelectedData(object sender, SqlDataSourceStatusEventArgs e)
{
gridViewTotalRowCount = e.AffectedRows;
}
protected void GridView1_DataBound(object sender, EventArgs e)
{
int pageRowsCount = GridView1.Rows.Count;
Total1.Text = "Showing 1 - " + pageRowsCount.ToString() + " of " + gridViewTotalRowCount.ToString();
}
private void BindGridView1()
{
try
{
this.GridView1.DataBind();
if (Convert.ToInt32(DropDownList1.SelectedValue) != null)
GridView1.PageSize = Convert.ToInt32(DropDownList1.SelectedValue);
}
catch (Exception ex)
{ throw ex; }
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindGridView1();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
BindGridView1();
}
}
If anyone could help that would be great. Thanks!
you could set paging information to Total1 text in onSelectedData handler as the following
protected void onSelectedData(object sender, SqlDataSourceStatusEventArgs e)
{
int startRowOnPage = (GridView1.PageIndex * GridView1.PageSize) + 1;
int lastRowOnPage = startRowOnPage + GridView1.Rows.Count - 1;
int totalRows = e.AffectedRows;
Total1.Text = "Showing " + startRowOnPage.ToString() +
" - " + lastRowOnPage + " of " + totalRows;
}
So you SQLDataSource should be like this sample:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
OnSelected="onSelectedData"
... >
</asp:SqlDataSource>
And you don't need to do anything for paging information in GridView1_DataBound.
I mean you could remove OnDataBound="GridView1_DataBound" out from your GridView declaration.
EDITED
To set the PageSize, you should set a default value for it such as the following sample:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Convert.ToInt32(DropDownList1.SelectedValue) != null)
GridView1.PageSize = Convert.ToInt32(DropDownList1.SelectedValue);
}
}
Since you are using SqlDataSource, try this code:
Protected Sub SqlDataSource1_Selected(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEvent Args) Handles
SqlDataSource1.Selected
Dim cnt As Integer = e.AffectedRows
End Sub

Categories

Resources