Ok guy,
i have made a simple program that has a web form where you fill in details fruit name, kg and cal count. i have then used session variables to get the fruit name from the form on default page and display them on about page in a drop down menu. that's all working fine, what i cant seem to work out is on the about page how to get it so the user selects a item from the drop down (created from form on default page) then enter a int how many they want (in text box) and have there selection and amount output on a list box on about page. il post the code i have so far any help would be much appreciated.
default page
public class Fruit
{
private string fName;
private int grams, calsPerGram;
private bool edible;
public Fruit(string n, int g, int c, bool e)
{
grams = g;
calsPerGram = c;
edible = e;
fName = n;
}
public int totalCalories()
{
return grams * calsPerGram;
}
public string getFruitInfo()
{
string s;
if (edible == true)
{
s = fName + " is yummy and it has " + totalCalories() +
"calories";
}
else
{
s = "Hands off! Not edible";
}
return s;
}
}
public partial class _Default : System.Web.UI.Page
{
List<Fruit> myBasket;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
myBasket = new List<Fruit>();
Session["listSession"] = myBasket;// seassion start
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
// Session["Fruitname"] = TbxName.Text; // my session i have made
MyFruit = Session["Fruitname"] as List<string>;
//Create new, if null
if (MyFruit == null)
MyFruit = new List<string>();
MyFruit.Add(TbxName.Text);
Session["Fruitname"] = MyFruit;
abc.Items.Clear();
Fruit f = new Fruit(TbxName.Text, int.Parse(TbxWeight.Text),
int.Parse(TbxCal.Text), CheckBox1.Checked);
myBasket = (List<Fruit>)Session["listSession"]; // session used
myBasket.Add(f);
foreach (var item in myBasket)
{
abc.Items.Add(item.getFruitInfo()); // List box used
}
}
public List<string> MyFruit { get; set; }
}
About page
public partial class About : Page
{
protected void Page_Load(object sender, EventArgs e)
{
MyFruit = Session["Fruitname"] as List<string>;
//Create new, if null
if (MyFruit == null)
MyFruit = new List<string>();
DropDownList1.DataSource = MyFruit;
DropDownList1.DataBind();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Drinklabel.Text = "Your Chosen Beverage is A " + DropDownList1.SelectedValue.ToString() + " Drink.";
}
public List<string> MyFruit { get; set; }
}
You do not necessarily need a separate class for calculating cost, but I recommend that you use a Label to display the selected fruit, amount desired and total price, like this in your About page:
Create a Button with Calculate text that has a click event handler, a calculatePrice method, a TextBox for quantity and a Label for display, like this:
protected void ButtonCalculate_Click(sender object, EventArgs e)
{
decimal total = calculatePrice(DropDownList1.SelectedItem.Text,
TextBoxQuantity.Text.Trim());
LabelResult.Text = "You would like " + TextBoxQuantity.Text.Trim() +
DropDownList1.SelectedItem.Text + "(s) for a total of $" +
total.ToString();
}
private decimal calculatePrice(string fruitName, int quantity)
{
// Ask the database for the price of this particular piece of fruit by name
decimal costEach = GoToDatabaseAndGetPriceOfFruitByName(fruitName);
return costEach * quantity;
}
Related
I have two form:
the first one "FrmAddRecordOfNonComplianceQHSE" has in load event this code
private async void FrmAddRecordOfNonComplianceQHSE_Load(object sender, EventArgs e)
{
KeyPreview = true;
txtCreationDate.EditValue = DateTime.Today;
DataTable DDt = await qhse.GetLastQHSEOrderNumberRecordOfNonCompliance().ConfigureAwait(true);
string RatingNumber = DDt.Rows[0][0].ToString();
txtOrderNumber.Text = RatingNumber;
cmbDetecteurStructure.Properties.DataSource = await qhse.GetEmployeesByDepartmentID(Program.FK_Department).ConfigureAwait(true);
cmbDetecteurStructure.Properties.DisplayMember = "Nom et Prénom";
cmbDetecteurStructure.Properties.ValueMember = "Matricule";
cmbRelevantStructure.Properties.DataSource = await qhse.Get_Department().ConfigureAwait(true);
cmbRelevantStructure.Properties.DisplayMember = "Département";
cmbRelevantStructure.Properties.ValueMember = "ID_Department";
}
and I have this code also
private void cmbRelevantStructure_Closed(object sender, ClosedEventArgs e)
{
BeginInvoke(new MethodInvoker(() => { cmbRelevantEmployee.EditValue = null; }));
}
private async void cmbRelevantEmployee_Enter(object sender, EventArgs e)
{
try
{
cmbRelevantEmployee.Properties.DataSource = await qhse.GetManagerByDepartmentID(Convert.ToInt32(cmbRelevantStructure.EditValue, CultureInfo.CurrentCulture)).ConfigureAwait(true);
cmbRelevantEmployee.Properties.DisplayMember = "Nom et Prénom";
cmbRelevantEmployee.Properties.ValueMember = "Matricule";
}
catch { }
}
and about the second form "FrmRecordOfNonComplianceQHSE" I have this code
FrmAddRecordOfNonComplianceQHSE frmQHSE = new FrmAddRecordOfNonComplianceQHSE();
and on DoubleClick of gridView1 I have this code
private async void gridView1_DoubleClick(object sender, EventArgs e)
{
//frmQHSE.cmbDetecteurStructure.Properties.DataSource = null;
frmQHSE.cmbDetecteurStructure.EditValue = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "FKDetecteur");
frmQHSE.txtCreationDate.EditValue = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "CreationDate");
frmQHSE.txtOrderNumber.Text = string.Empty;
frmQHSE.txtOrderNumber.Text = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "OrderNumber").ToString();
frmQHSE.cmbRelevantStructure.EditValue = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "RelevantDepartment");
frmQHSE.cmbRelevantEmployee.Enter += new EventHandler(cmbRelevantEmployee_Enter);
frmQHSE.cmbRelevantEmployee.EditValue = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "FKRelevant");
if (frmQHSE == null || frmQHSE.IsDisposed)
frmQHSE = new FrmAddRecordOfNonComplianceQHSE();
frmQHSE.ShowDialog();
}
and I have this code also
private async void cmbRelevantEmployee_Enter(object sender, EventArgs e)
{
try
{
frmQHSE.cmbRelevantEmployee.Properties.DataSource = await qhse.GetManagerByDepartmentID(Convert.ToInt32(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "RelevantDepartment"), CultureInfo.CurrentCulture)).ConfigureAwait(true);
frmQHSE.cmbRelevantEmployee.Properties.DisplayMember = "Nom et Prénom";
frmQHSE.cmbRelevantEmployee.Properties.ValueMember = "Matricule";
}
catch { }
}
Now when I DoubleClick on gridView1 row the first form open but the controls get the values from the load event of that form not the values of gridView1 of my second form.
How can solve this problem ?.
Thanks in advance.
Either use data binding and assign an object to DataSource or assign values to the controls, but do not mix both approaches.
I assume that GetManagerByDepartmentID now returns a DataTable or something like this, since you have display member names with spaces. Create data classes instead. This makes it easier to manipulate the data. Something like this
public class Employee
{
public string NomPrénom { get; set; }
public int Matricule { get; set; }
public string Département { get; set; }
public int ID_Department { get; set; }
...
}
Now, you can let GetManagerByDepartmentID return an Employee object. Your form binds to an Employee object and your grid can bind to an Employee object. Or at least you can create and fill such an object manually and assign it to the DataSource of the first form.
private async void gridView1_DoubleClick(object sender, EventArgs e)
{
var emp = new Employee {
FKDetecteur = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "FKDetecteur"),
CreationDate = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "CreationDate"),
OrderNumber gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "OrderNumber").ToString(),
....
};
frmQHSE.EmployeeBindingSource.DataSource = emp;
frmQHSE.ShowDialog();
}
Use BindingSourcees in conjunction with object data sources on your from. This allows you to set DisplayMembers and ValueMembers in the forms designer.
I have a Class where there a 2 variables int ID and string name. I made a list of several objects and loaded them onto a listbox. The listbox only show the name. Is there a way to retrieve the ID from the listbox?
class Show
{
private int _Id;
private string _Naam;
private string _Genre;
public override string ToString()
{
return Naam;
}
}
from a database i make a list of objects.
private void bttn_zoek_Click(object sender, EventArgs e)
{
foreach (object a in List<show> List)
{
listbox1.Items.Add(a);
}
}
I hope this is enough
Assuming WinForms, here is a super simple example of overriding ToString() to control how the class is displayed in the ListBox, and also how to cast the selected item in the ListBox back to your class type so you can extract values from it. There are other ways to accomplish this task, but you should understand a bare bones example like this first:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SomeClassName sc1 = new SomeClassName();
sc1.ID = 411;
sc1.Name = "Information";
listBox1.Items.Add(sc1);
SomeClassName sc2 = new SomeClassName();
sc2.ID = 911;
sc2.Name = "Emergency";
listBox1.Items.Add(sc2);
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
SomeClassName sc = (SomeClassName)listBox1.Items[listBox1.SelectedIndex];
label1.Text = "ID: " + sc.ID.ToString();
label2.Text = "Name: " + sc.Name;
}
}
}
public class SomeClassName
{
public int ID;
public string Name;
public override string ToString()
{
return ID.ToString() + ": " + Name;
}
}
Posting some of your code would be nice. Have you tried listBox.items[index].ID?
Here I'm assuming that index is whatever index you're currently searching for.
You can also try listBox.SelectedItem[index].ID if you're doing something like an event.
I have this code on my asp net page (it´s an url with an id www.example.com/GestHC.aspx?pID=36006394 )
public partial class GestHC : WebPart
{
public GestHC ()
{
}
static int iIDHC;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
InitializeControl();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.Page.IsPostBack)
{
iIDHC = -1;
string str = this.Page.Request["pID"];
iIDHC = int.Parse(str.Replace("'", ""));
MyModel hc = MyModel.readdata(iIDHC);
this.txtName.text = hc.name
this.txtSurname.text = hc.surname
...
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
MyModel hc = new MyModel();
if (iIDHC != -1)
{
hc = MyModel.readdata(iIDHC);
}
else
{
hc.name = txtname.text;
hc.surname = txtSurname.text;
}
hc.dir1 = dir.text;
...
hc.savedata()
}
catch (Exception)
{
this.navegarAGridMensaje("Error");
}
}
}
The problem is that when user loads the data and saves it, everything works fine but when more than 2 user or browsers works together the data is mixed. For example:
User a creates:
ID = 10
Name = XXX
Age = 8
User b creates:
ID = 11
Name = YYY
Age = 10
Then if user a updates his data (ID=10), maybe setting the Age to 80 the result is
User a creates:
ID = 10
Name = XXX
Age = 8
User b creates:
ID = 11
Name = YYY
Age = 88
So the (ID=11) is updated. Debuggin.. I could see that with an static id, when the second user loads it can read the previous user iIDHC....
How to avoid this problem?
You can use Session object instead (https://msdn.microsoft.com/en-us/library/ms178581.aspx).
When you are store your data in static variable - it will be shared between all users in your app.
Make it non static!
public partial class GestHC : WebPart
{
public GestHC ()
{
}
private int iIDHC = -1;//initialize here
...
}
also you dont have to initialize in page load
protected void Page_Load(object sender, EventArgs e)
{
//iIDHC = -1; - not required as you can initialize it during declaration
}
I am making an online form. I initialise 4 variables in my code at the beginning. When I select a dropdown, an event (DropDownList4_SelectedIndexChanged ) gets fired which in turn call Availability(). Here my boolean variable avail_bus is assigned a value. However, when i click on submit button ( Button1_Click1), the variable avail_bus is reinitialised to false. I debugged this and found out that upon clicking on Submit(Button1_Click1) the control first goes to the top of the code in the page which is
public partial class Appform : System.Web.UI.Page
{
private bool isNotDup = true;
private bool avail_bus ;
private int max_capacity_bus;
private int realAvailability;
}
and then goes to Button1_click1 .
How can I prevent this from happening ? If the state of avail_bus is changed to true while calling availability, it should not get reinitialized to true when i click on submit.
Below is my code :
namespace eTransport
{
public partial class Appform : System.Web.UI.Page
{
private bool isNotDup = true;
private bool avail_bus ;
private int max_capacity_bus;
private int realAvailability;
protected void Page_Load (object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BindDropDown();
}
}
//Method called when dropdown is selected in Bus Stop. It helps to populate Bus Number
protected void DropDownList4_SelectedIndexChanged (object sender, EventArgs e)
{
AutoPopulateBusStop();
Availability();
}
//Method to load drop down values in Bus Stop. These are populated from database
protected void BindDropDown ()
{
//some code here
}
//Method to autopopulate Bus Number based on selection of Bus Stop. The mapping is in the database in the table named -> dropdownlist
protected void AutoPopulateBusStop ()
{
//some code here
}
protected void Availability ()
{
string constr5 = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (SqlConnection con5 = new SqlConnection(constr5))
{
try
{
using (SqlCommand cmd5 = new SqlCommand("select count(*) from etms where BusNo='" + TextBox6.Text.ToString() + "'"))
{
cmd5.CommandType = CommandType.Text;
cmd5.Connection = con5;
con5.Open();
int capacity_from_db = Convert.ToInt16(cmd5.ExecuteScalar());
realAvailability = max_capacity_bus - capacity_from_db;
if (realAvailability > 0)
{
avail_bus = true;
TextBox2.Text = realAvailability.ToString() + " seats available ";
TextBox2.ForeColor = System.Drawing.ColorTranslator.FromHtml("#008000");
}
else
{
TextBox2.Text = "Seats Not available. Please choose another Stop";
TextBox2.ForeColor = System.Drawing.ColorTranslator.FromHtml("#ff1919");
}
}
}
catch (Exception ex)
{
Response.Write(ex);
}
}
}
protected void Button1_Click1 (object sender, EventArgs e)
{
if (isNotDup)
{
if (avail_bus)
{
// Submit the Form
}
else
{
Label14.Text = "Bus Seats not available!";
Label15.Text = null;
}
}
}
protected void PhoneNumberValidatation (object source, ServerValidateEventArgs args)
{
//some code here
}
}
}
There are three possible solution for this question.
Static - This will create one instance that accessible to all pages (Global).
private static avail_bus = true;
Session State - This enables you to store and retrieve values for a user as the user navigates.
// Get...
private bool avail_bus = (bool)Session["avail_bus"];
// Set
Session["avail_bus"] = true;
Control.ViewState - Gets a dictionary of state information that allows you to save and restore the view state of a server control across multiple requests for the same page.
public bool avail_bus
{
get { return ViewState["avail_bus"] == null ? false : (bool)ViewState["avail_bus"]; }
set { ViewState["avail_bus"] = value; }
}
Every time there is a request for your page, a new instance of that page-class is created to handle that request. So any fields are re-initialized.
You can store a value in ViewState to remember a value over various requests:
namespace eTransport
{
public partial class Appform : System.Web.UI.Page
{
private bool isNotDup
{
set { ViewState["isNotDup "] = value; }
get
{
if (ViewState["isNotDup "] == null)
return true;
return (bool )ViewState["isNotDup "];
}
}
private bool avail_bus
{
set { ViewState["avail_bus"] = value; }
get
{
if (ViewState["avail_bus"] == null)
return true;
return (bool )ViewState["avail_bus"];
}
}
private int max_capacity_bus
{
set { ViewState["max_capacity_bus "] = value; }
get
{
if (ViewState["max_capacity_bus "] == null)
return 0;
return (int)ViewState["max_capacity_bus "];
}
}
private int realAvailability
{
set { ViewState["realAvailability"] = value; }
get
{
if (ViewState["realAvailability"] == null)
return 0;
return (int)ViewState["realAvailability"];
}
}
protected void Page_Load (object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BindDropDown();
}
}
//Method called when dropdown is selected in Bus Stop. It helps to populate Bus Number
protected void DropDownList4_SelectedIndexChanged (object sender, EventArgs e)
{
AutoPopulateBusStop();
Availability();
}
//Method to load drop down values in Bus Stop. These are populated from database
protected void BindDropDown ()
{
//some code here
}
//Method to autopopulate Bus Number based on selection of Bus Stop. The mapping is in the database in the table named -> dropdownlist
protected void AutoPopulateBusStop ()
{
//some code here
}
protected void Availability ()
{
string constr5 = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (SqlConnection con5 = new SqlConnection(constr5))
{
try
{
using (SqlCommand cmd5 = new SqlCommand("select count(*) from etms where BusNo='" + TextBox6.Text.ToString() + "'"))
{
cmd5.CommandType = CommandType.Text;
cmd5.Connection = con5;
con5.Open();
int capacity_from_db = Convert.ToInt16(cmd5.ExecuteScalar());
realAvailability = max_capacity_bus - capacity_from_db;
if (realAvailability > 0)
{
avail_bus = true;
TextBox2.Text = realAvailability.ToString() + " seats available ";
TextBox2.ForeColor = System.Drawing.ColorTranslator.FromHtml("#008000");
}
else
{
TextBox2.Text = "Seats Not available. Please choose another Stop";
TextBox2.ForeColor = System.Drawing.ColorTranslator.FromHtml("#ff1919");
}
}
}
catch (Exception ex)
{
Response.Write(ex);
}
}
}
protected void Button1_Click1 (object sender, EventArgs e)
{
if (isNotDup)
{
if (avail_bus)
{
// Submit the Form
}
else
{
Label14.Text = "Bus Seats not available!";
Label15.Text = null;
}
}
}
protected void PhoneNumberValidatation (object source, ServerValidateEventArgs args)
{
//some code here
}
}
}
You can store the availability status in a hidden input field which later gets posted on Button1 click event.
And in button1 click event instead of accessing the avail value from variable access it from hiddenField's value
Another option would be calling Availability() again in click event of button1 as a first line so that it sets proper value in the avail_bus variable
thanks in advance for any help!
A bit of background basically I am building an application that stores vehicles (cars,truck,buses), I have a vehicle superclass and all the individual classes (car.cs, truck.cs, minibus.cs) inherit from this super class.
I also have a class called 'fleet' that I would like to add the vehicles to an then display the results in a list box.
I have everything else working but I cannot get the trucks and minibus's to update and display on the list box like the cars do.
Here is my fleet class which includes the car.cs; and it works fine and the data taken from the car form gets added and displayed in the listbox.
class Fleet
{
private List<Vehicle> theFleet = new List<Vehicle>();
public List<Vehicle> fleet
{
get
{
return theFleet;
}
}
public void deleteFromFleet(Vehicle aCar)
{
theFleet.Remove(aCar);
}
public void addToFleet(Vehicle aCar)
{
theFleet.Add(aCar);
}
}
Here is my main form, that has the list box on it:
public partial class FrmHireCo : Form
{
private Fleet myFleet = new Fleet();
private ClientList mycustomer = new ClientList();
//Fleet object used to store cars
public FrmHireCo()
{
//Default constructor
InitializeComponent();
}
private void updateFleetList()
{
lstFleet.Items.Clear();
foreach (Car c in myFleet.fleet)
{
string line = "Car: " + c.make+" " + c.colour;
lstFleet.Items.Add(line);
}
}
private void updateClientList()
{
customers.Items.Clear();
foreach (Customer c in mycustomer.clientlist)
{
string line = "Customer: " + c.name + " " + c.address;
customers.Items.Add(line);
}
}
private void btnAddCar_Click(object sender, EventArgs e)
{
//Add a new car
FrmCar carGui = new FrmCar(); //Form used to add new car
carGui.ShowDialog();
Car myCar = carGui.car; //Get new car from form
myFleet.addToFleet(myCar); //Add to fleet list
updateFleetList(); //Uodate fleet list
}
private void lstFleet_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstFleet.SelectedIndex > -1)
{
int index = lstFleet.SelectedIndex;
Car myCar = myFleet.fleet.ElementAt(index);
FrmCar carGui = new FrmCar();
carGui.car = myCar;
carGui.Show();
}
}
private void btnCustomer_Click(object sender, EventArgs e)
{
FrmCustomer customerGui = new FrmCustomer();
customerGui.ShowDialog();
Customer mycustomer = customerGui.customer;
mycustomer.addToClientList(mycustomer);
updateFleetList();
}
private void customers_SelectedIndexChanged(object sender, EventArgs e)
{
if (customers.SelectedIndex > -1)
{
int index = customers.SelectedIndex;
Customer myCustomer = mycustomer.clientlist.ElementAt(index);
FrmCustomer customerGui = new FrmCustomer();
customerGui.customer = myCustomer;
customerGui.Show();
}
}
}
Cheers for any help!
private void updateFleetList()
{
lstFleet.Items.Clear();
foreach (Vehicle c in myFleet.fleet)
{
string line = "Car: " + c.make+" " + c.colour;
lstFleet.Items.Add(line);
}
}
You should include all vehicles.
private void updateFleetList()
{
lstFleet.Items.Clear();
foreach (Vehicle v in myFleet.fleet)
{
lstFleet.Items.Add(v);
}
}
Also, just override ToString in all your Vehicle subclasses and the ListBox will use that inherently; this way not every Vehicle needs a Make or Color property.