static variable get parameter - c#

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
}

Related

Filling one form from another does not get all values from the second form

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.

Variables getting reinitialised when clicking on Button in C#

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

How to pass data between WPF forms

I need help passing data from one WPF form to another. I have a main window with two other windows that will prompt the user for information. I want to end up with all the information in the first form so that I can store the data later on. The second form must return the Reservation and Room information when you click the OK button on the second form. The third form must return the Person information when you click OK.
public partial class MainWindow : Window
{
private string message;
public MainWindow()
{
InitializeComponent();
}
protected void Exit_Click(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
protected void Create_Reservation_Click(object sender, RoutedEventArgs e)
{
Reservation PersonReservation = new Reservation();//Create a reservation instance
Room PersonRoom = new Room(); //Create an instance of a room
Person myPerson = new Person();//Create an instance of a person
CreateResRoom createReservationRoom = new CreateResRoom();//Create a instance of the CreateReservation WPF Form
createReservationRoom.Show();
Here it is supposed to set the room, reservation and person instance that I created equil to their corresponding instances in the CreateResRoom class.
I think the problem lies here, because it keeps continuing before it opens the CreateResRoom form.
PersonRoom = createReservationRoom.myRoom;
PersonReservation = createReservationRoom.myReservation;
}
}
That was my first class, the second and third will follow.
public partial class CreateResRoom : Window
{
Person myPerson;
public CreateResRoom()
{
InitializeComponent();
myReservation = new Reservation();
myRoom = new Room();
myPerson = new Person();
}
public Room myRoom
{
get;
set;
}
public Reservation myReservation
{
get;
set;
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void btnOk_Click(object sender, RoutedEventArgs e)
{
myRoom.RoomBeds = txtHeadCount.Text;
myRoom.RoomNumber = 1;
myRoom.RoomPrice = 20;
myRoom.RoomType = cboRoomType.Text;
myReservation.ResEndDate = dpEnd.ToString();
myReservation.ResStartDate = dpStart.ToString();
CreateRes createReservation = new CreateRes();
createReservation.Show();
//I think the same problem lies here that is in the MainWindow.
myPerson = createReservation.myPerson;
this.Close();
}
}
And the last class follows:
public partial class CreateRes : Window
{
public Person myPerson
{
get;
set;
}
public CreateRes()
{
InitializeComponent();
myPerson = new Person();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
private void btnOk_Click(object sender, RoutedEventArgs e)
{
myPerson.FirstName = txtFName.Text;
myPerson.LastName = txtLName.Text;
myPerson.IdNumber = Convert.ToInt32(txtIdNumber.Text);
myPerson.PhoneNumber = Convert.ToInt32(txtPhoneNumber.Text);
myPerson.AddressCity = txtAddressCity.Text;
myPerson.AddressStreet = txtAddressStreet.Text;
myPerson.AddressProvince = txtAddressProvince.Text;
myPerson.AddressPostalCode = txtAddressPostalCode.Text;
this.Close();
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
Just make a overload constructor which takes parameters of the window in which you want to retrieve.
Example:
Suppose we want a user to login from our MainWindow( i.e Login Window ) and we want to pass an int ID / string Email to our second form to retrieve data of logging user.
Than We have to first overload our second wpf form constructor. You can either make default constructor to do this or make an overload constructor for this work.
SecondForm:
public secondForm()
{
//Your Default Constructor Logic
}
public secondForm(string email_ )
{
//Your Overload Constructor Logic
}
Now in MainWindow from where we are logging and passing our EMail
MainWindow:
public void btnLogin()
{
//On Success
SecondWindow sw = new SecondWindow(txtBoxEMail.Content);
sw.Show();
}
A pattern you can use for this sort of thing is to have each form be responsible for creating the instance on ok click and then provide the object via a property get.
public partial class SomeForm: Window
{
public SomeClass MyProperty { get; private set; }
private void btnOk_Click(object sender, RoutedEventArgs e)
{
this.MyProperty = new SomeClass();
//additional setter logic here
this.Close();
}
}
Then you would access it from a parent form like this (notice the use of ShowDialog() http://msdn.microsoft.com/en-us/library/system.windows.window.showdialog(v=vs.110).aspx for easy checking of whether ok was clicked or not).
protected void Create_Reservation_Click(object sender, RoutedEventArgs e)
{
SomeClass myObj;
SomeOtherClass myOtherObj;
SomeForm myForm = new SomeForm();
if(myForm.Show().Value)
{
myObj = myForm.MyProperty;
}
SomeOtherForm myOtherForm = new SomeOtherForm();
if(myOtherForm.ShowDialog().Value)
{
myOtherObj = myOtherForm.MyOtherProp;
}
//save myObj & myOtherObj or whatever you need to do with them
Use the "normal way", here is a short overview.
First create a Data Context:
public class DC_Reservation() : INotifyPropertyChanged {
protected Reservation _PersonReservation ;
public Reservation PersonReservation {
get { return _PersonReservation ; }
set {
_PersonReservation = value;
NotifyPropertyChanged("PersonReservation ");
}
}
protected Room _PersonRoom ;
public Room PersonRoom {
get { return _PersonRoom ; }
set {
_PersonRoom = value;
NotifyPropertyChanged("PersonRoom");
}
}
protected Person _myPerson ;
public Person myPerson {
get { return _myPerson ; }
set {
_myPerson = value;
NotifyPropertyChanged("myPerson ");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged( string PropertyName ) {
if ( PropertyChanged != null ) {
PropertyChanged( this, new PropertyChangedEventArgs( PropertyName ) );
}
}
}
In the MainWindows you can assign and use the dataContext :
public partial class MainWindow : Window {
DC_Reservation dataContext {
get { return DataContext as DC_Reservation; }
}
private string message;
public MainWindow() {
InitializeComponent();
DataContext = new DC_Reservation();
}
protected void Create_Reservation_Click(object sender, RoutedEventArgs e) {
dataContext.PersonReservation = new Reservation();//Create a reservation instance
dataContext.PersonRoom = new Room(); //Create an instance of a room
dataContext.myPerson = new Person();//Create an instance of a person
CreateResRoom createReservationRoom = new CreateResRoom();//Create a instance of the CreateReservation WPF Form
// I'm not sure whether the next line is required.
createReservationRoom.DataContext = DataContext;
createReservationRoom.Show();
}
}
You can assign the DataContext in the constructor, but I think the better way is to define the DataContext in the MainWindow, in the other windows you can use the DesignContext:
<Window.DataContext>
<local:DC_Reservation />
</Window.DataContext>
So you can use the same DataContext over all forms ...
With DataBindings you can bind the input to the field:
<TextBox Text="{Binding FirstName, Path=myPerson, Mode=TwoWay}" />
I found another answer that Zarathos posted Jan 16 '13 at 21:43
for a different question
Use a public static class and access it from anywhere.
public static class Globals
{
public static String s_Name = "Mike"; //Modifiable in Code
public const int32 VALUE = 10; // unmodifiable
}
Then you can use it anywhere, provided you are working on the same namespace
string name = Globals.s_Name;

asp.net c# using session data to output more data

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;
}

storing selected value to enumtype

I a have a page that has enumtype. the following is the code in aspx.cs inside the pageload
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
RegardingObject();
ListItem selectedType = dropRegarding.Items.FindByValue(Event.RegardingObjectType.ToString());
if(selectedType!=null)
{
selectedType.Selected = true;
}
the following to populate dropdownlist
private void RegardingObject()
{
dropRegarding.Items.Add(new ListItem("UnknownOrNone","0"));
dropRegarding.Items.Add(new ListItem("LiveTrack", "10"));
dropRegarding.Items.Add(new ListItem("Activity", "11"));
}
while saving it back i am using
Event.RegardingObjectType = (EnumTypes)Enum.Parse(typeof(EnumTypes),
dropRegarding.SelectedItem.ToString());
getting cannot implicitly convert type 'datacontracts.enumtypes' to 'datacontracts.enumtypes.regardingobjecttype'
in datacontracts.enumtypes.cs i have
public class EnumTypes
{
public enum RegardingObject
{
UnknownOrNone = 0,
LiveTrack = 10,
Activity = 11
}
}
That's because EnumTypes isn't an enum, RegardingObject is:
Event.RegardingObjectType = (EnumTypes.RegardingObject)Enum.Parse(typeof(EnumTypes.RegardingObject),
dropRegarding.SelectedItem.ToString());
this does it
Event.RegardingObjectType = (EnumTypes.RegardingObjectType)Enum.Parse(typeof(EnumTypes.RegardingObjectType),
dropRegarding.SelectedItem.ToString());
its EnumTypes.regardingobjecttype instead of enumtypes

Categories