C# how to create class instance for entire GUI - c#

I am making a simple reservation system that uses a GUI for input and display with a class for all the logic and storing of available/taken seats. My problem I do not know how to create on instance of the class when the form loads to be used by the entire GUI. I have, however done this with the button click, but every time the button is clicked the stored data in the class is reset. How do I create an instance of the class when the form loads that will not reset the data whenever the button is clicked. Below is the code for my GUI with a work around for my data being reset. Thanks for the help and if I missed a related topic while searching before posting please let me know.
namespace AirLine
{
public partial class ReservationSystem : Form
{
public ReservationSystem()
{
InitializeComponent();
radioFirst.Checked = true; // start program with button checked
}
private void buttonBook_Click(object sender, EventArgs e)
{
Label[] labelFirst = new Label[] { labelFirst1, labelFirst2, labelFirst3, labelFirst4, labelFirst5 };
Label[] labelEcon = new Label[] { labelEcon1, labelEcon2, labelEcon3, labelEcon4, labelEcon5 };
CheckBox[] checkFirst = new CheckBox[] { checkFirst1, checkFirst2, checkFirst3, checkFirst4, checkFirst5 };
CheckBox[] checkEcon = new CheckBox[] { checkEcon1, checkEcon2, checkEcon3, checkEcon4, checkEcon5 };
Reservation res = new Reservation();
int x;
int i = 0; // counter for bool update
int k = 0; // counter for manual seat slecetion FirstClass
int c = 0; // counter for manual seat selection Econ
int j = 0; // counter to reset unchecked boxes
while (i < checkFirst.Length) //update fseats bool
{
if (checkFirst[i].Checked == true) //if box chceked correspsonding bool change to true
{
res.reserveFirstClassSeat(i);
}
if (checkEcon[i].Checked == true) //if box chceked correspsonding bool change to true
{
res.reserveEconomyClassSeat(i);
}
++i; // tick i
}
//booking of first avialible seat
try
{
string firstname = textFirst.Text;
string lastname = textLast.Text;
int age = Convert.ToInt32(textAge.Text);
string name = firstname + lastname + age;
if (textFirst.Text != "" && textLast.Text != "" && Enumerable.Range(1, 150).Contains(age)) //validate user input
{
if (radioFirst.Checked == true) //User selected first class
{
if (res.isFirstClassAvailable() == false && res.isEconomyClassAvailable() == true)
{
System.Windows.Forms.MessageBox.Show("First Class is full, Only Economy left"); // if first class is full inform user
}
if (res.isFirstClassAvailable() == true ) // verify a seat is open in first class
{
x = res.nextAvailableFirstClassSeat(); // store next availible seat number
res.reserveFirstClassSeat(x); // resevere next availible seat
checkFirst[x].Checked = true; // check checkbox of seat
labelFirst[x].Text = name; //Change label to reflect name and age of passenger
}
}
if (radioEcon.Checked == true) //User selected Econ class
{
if (res.isFirstClassAvailable() == true && res.isEconomyClassAvailable() == false)
{
System.Windows.Forms.MessageBox.Show("Economy is full, Only First Class left"); // if econ is full inform user
}
if (res.isEconomyClassAvailable() == true) // verify a seat is open in first class
{
x = res.nextAvailableEconomyClassSeat(); // store next availible seat number
res.reserveEconomyClassSeat(x); // resevere next availible seat
checkEcon[x].Checked = true; // check checkbox of seat
labelEcon[x].Text = name; //Change label to reflect name and age of passenger
}
}
}
else // if input is not valid
{
System.Windows.Forms.MessageBox.Show("Please Check Name, Age, and Seat #");
}
}
catch (FormatException)
{
System.Windows.Forms.MessageBox.Show("Please Check Name, Age, and Seat #");
}
// manual check of seat
try
{
string firstname = textFirst.Text;
string lastname = textLast.Text;
int age = Convert.ToInt32(textAge.Text);
string name = firstname + lastname + age;
if (textFirst.Text != "" && textLast.Text != "" && Enumerable.Range(1, 150).Contains(age)) //validate user input
{
if (radioManual.Checked == true)
{
while (k < checkFirst.Length)
{
if (checkFirst[k].Checked == true && labelFirst[k].Text == "Open") // see if box was checked and label is still "Open"
{
res.reserveFirstClassSeat(k);
labelFirst[k].Text = name;
}
++k;
}
while (c < checkEcon.Length)
{
if (checkEcon[c].Checked == true && labelEcon[c].Text == "Open")
{
res.reserveEconomyClassSeat(c);
labelEcon[c].Text = name;
}
++c;
}
}
}
else // if input is not valid
{
System.Windows.Forms.MessageBox.Show("Please Check Name, Age, and Seat #");
}
}
catch (FormatException)
{
System.Windows.Forms.MessageBox.Show("Please Check Name, Age, and Seat #");
}
if (res.isFirstClassAvailable() == false && res.isEconomyClassAvailable() == false) // if flight is full inform user
System.Windows.Forms.MessageBox.Show("Flight is Full");
{ // clear text boxes
textFirst.Text = "";
textLast.Text = "";
textAge.Text = "";
}
}
private void buttonUpdate_Click(object sender, EventArgs e)
{
Label[] labelFirst = new Label[] { labelFirst1, labelFirst2, labelFirst3, labelFirst4, labelFirst5 };
Label[] labelEcon = new Label[] { labelEcon1, labelEcon2, labelEcon3, labelEcon4, labelEcon5 };
CheckBox[] checkFirst = new CheckBox[] { checkFirst1, checkFirst2, checkFirst3, checkFirst4, checkFirst5 };
CheckBox[] checkEcon = new CheckBox[] { checkEcon1, checkEcon2, checkEcon3, checkEcon4, checkEcon5 };
int j = 0;
while (j < checkFirst.Length)
{
if (checkFirst[j].Checked == false)
{
labelFirst[j].Text = "Open";
}
if (checkEcon[j].Checked == false)
{
labelEcon[j].Text = "Open";
}
++j;
}
}
}
}

To use the instance of myClass in the entire GUI do the following.
public partial class MainWindow : Window
{
MyClass myClass;
public MainWindow()
{
myClass = new MyClass();
InitializeComponent();
}
}

Related

How do i create a class (other file) that will enable and Check my Checkboxes?

I am new to C#.
I have written a code that makes the other Checkbox true and RichTextBox enable. (Successfully working fine).
Now I don't want to repeat this whole coding so I decided to create a class (this class is a new file - [like a function in JS] ) but I don't know how to execute it effectively.
The CheckBoxes and RichTextBoxes are all in my Main Form. So this Class will be called out in my Main Form.
below is my coding kindly correct my code.
Public Static String checkBox_RichtextBox(int x, string cb_name, string rtb_name){
for (int i = x; i < 21; i++)
{
var cb_ctrl = Main_Form.Controls.Find("L_CB" + i, true).FirstOrDefault() as CheckBox;
var rtb_ctrl = Main_Form.Controls.Find("textBox_L" + i, true).FirstOrDefault() as RichTextBox;
if (i == x)
{
if (cb_ctrl != null)
{
return cb_ctrl.Checked = true;
return rtb_ctrl.Enabled = true;
}
else if (i > 1)
{
return cb_ctrl.Checked = false;
return rtb_ctrl.Enabled = false;
}
}
}
}
You can create a class something like below
class Checkbox_RichTextBoxHandler
{
public void checkBox_RichtextBox(int x, CheckBox cb_ctrl, RichTextBox rtb_ctrl)
{
if (cb_ctrl != null)
{
cb_ctrl.Checked = true;
rtb_ctrl.Enabled = true;
}
else if (x > 1)
{
cb_ctrl.Checked = false;
rtb_ctrl.Enabled = false;
}
}
}
Then in your function you can call like below
Public Static String checkBox_RichtextBox(int x, string cb_name, string rtb_name){
Checkbox_RichTextBoxHandler cbHandler;
for (int i = x; i < 21; i++)
{
var cb_ctrl = Main_Form.Controls.Find("L_CB" + i, true).FirstOrDefault() as CheckBox;
var rtb_ctrl = Main_Form.Controls.Find("textBox_L" + i, true).FirstOrDefault() as RichTextBox;
if (i == x)
{
cbHandler.checkBox_RichtextBox(i, cb_ctrl, rtb_ctrl);
}
}
//Return status string per your needs
}
You can use the following class to check and enable the CheckBox and RichTextBox respectively in Main_Form or any other class.
class YourClassName
{
public static void checkBox_RichtextBox(Form form, int x, string cb_name, string rtb_name)
{
CheckBox cb_ctrl = form.Controls.Find(cb_name + x, true).FirstOrDefault() as CheckBox;
var rtb_ctrl = form.Controls.Find(rtb_name + x, true).FirstOrDefault() as RichTextBox;
if (cb_ctrl != null)
{
cb_ctrl.Checked = true;
rtb_ctrl.Enabled = true;
}
}
}
Now in the Main_Form you only have to pass the Main_Form object and CheckBox_RichTextBox group names and number like YourClassName.checkBox_RichtextBox(this, number, "L_CB", "textBox_L"). If you want to check and enable all of the CheckBox and RichTextBox respectively then use a loop.
for (int i = 0; i < 21; i++) {
YourClassName.checkBox_RichtextBox(this, i, "L_CB", "textBox_L");
}

to store and keep values of variable even after event is finished in c#

this code is called upon a button click in a windows form and the values are stored after button click and disappear after the event ends and go back to default values but I want the values to remain as i have to use them somewhere else....any suggestions?Also I want to retain the current state of the form and not use a new instance each time
showval function called and the value of variable bitwise is changed there
class Profile{
public bool GetProfileFilter()
{
frmInactiveView frmInactive = new frmInactiveView();
if (frmInactive.btnApplyWasClicked == true || frmInactive.btnCancelWasClicked == false)
{
frmInactive.ShowVal();
MessageBox.Show("bit:" + IBitWise);
MessageBox.Show("ST:" + BegDate);
MessageBox.Show("ET:" + EndDate);
return true;
}
else
{
return false;
}
}
}
enter code here
public partial class FilterView : Form{
Profile profile = new Profile();
private void btnApply_Click(object sender, EventArgs e)
{
btnApplyWasClicked = true;
ShowVal();
status = profile.GetProfileFilter();
profile.ShowMe();
Btn_Enable();
this.Close();
}
public void ShowVal()
{
if (btnApplyWasClicked == true || btnCancelWasClicked == false)
{
if (chkCancel.Checked == true)
{
profile.IBitWise += 2;
}
if (chkDiscon.Checked == true)
{
profile.IBitWise += 1;
}
if (chkVoidwoRes.Checked == true)
{
profile.IBitWise += 4;
}
if (chkVoidwRes.Checked == true)
{
profile.IBitWise += 8;
}
}
}
}
The problem is your form getting instantiated every time when GetProfileFileter is called.
To avoid it, put instance of frmInactiveView under your Profile class. Then value of frmInactiveView would only be renewed when a new Profile is instantiated.
class Profile{
// Keep your form instance here
frmInactiveView frmInactive = new frmInactiveView();
public bool GetProfileFilter()
{
// Don't new it again!
//frmInactiveView frmInactive = new frmInactiveView();
DialogResult result = frmInactive.ShowDialog();
// You may need to take care of dialog result if someone clicked cancel.
if (frmInactive.btnApplyWasClicked == true || frmInactive.btnCancelWasClicked == false)
{
frmInactive.ShowVal();
MessageBox.Show("bit:" + IBitWise);
MessageBox.Show("ST:" + BegDate);
MessageBox.Show("ET:" + EndDate);
return true;
}
else
{
return false;
}
}
}

How can I make the strings from the list translate to each other?

I have two lists with different strings. One list contains strings in one language and the other lists contains their translation. I've been stuck on this for ages(even tried using Dictionary<> but then had a problem with the random part)
How can I make the strings match each other to make a memory word based game?
Random random = new Random();
List<string> EngBasicPhrases = new List<string>()
{
"Hello", "How are you?", "Hot", "Thank you", "Welcome",
"Let's go", "My name is...", "Cold", "Good luck",
"Congratulations", "Bless you","I forgot","Sorry","I'm fine",
"It's no problem","Don't worry","Here it is","What?","Of course",
"Boy","Girl","Man","Woman","Friend","Almost","Late"
};
List<string> FrBasicPhrases = new List<string>()
{
"Salut","Ca va?","Chaud", "Merci", "Bienvenu", "Allons-y","Je m'appelle","Du froid",
"Bonne chance","Felicitations","A vos souhaits","J'ai oublie","Desole","Je vais bien",
"Ce n'est pas grave","Ne t'en fais pas","Voila","Comment?","Bien sur","Un garcon","Une fille",
"Un home","Une femme","Un ami","Presque","En retard"
};
Button firstClicked, secondClicked;
public Game()
{
InitializeComponent();
AssignWordsToSquares();
EngBasicPhrases.AddRange(FrBasicPhrases);
}
public void AssignWordsToSquares()
{
Button button1 = button2;
int randomNumber;
string[] phrases = EngBasicPhrases.ToArray();
for (int i = 0; i < tableLayoutPanel1.Controls.Count; i++)
{
if (tableLayoutPanel1.Controls[i] is Button)
button1 = (Button)tableLayoutPanel1.Controls[i];
else
continue;
randomNumber = random.Next(0, EngBasicPhrases.Count - 1);
button1.Text = phrases[randomNumber];
EngBasicPhrases.RemoveAt(randomNumber);
}
phrases = FrBasicPhrases.ToArray();
for (int i = 0; i < tableLayoutPanel2.Controls.Count; i++)
{
if (tableLayoutPanel2.Controls[i] is Button)
button2 = (Button)tableLayoutPanel2.Controls[i];
else
continue;
randomNumber = random.Next(0, FrBasicPhrases.Count);
button2.Text = phrases[randomNumber];
FrBasicPhrases.RemoveAt(randomNumber);
}
}
private void Button_Click(object sender, EventArgs e)
{
if (firstClicked != null && secondClicked != null)
return;
Button clickedButton = sender as Button;
if (clickedButton == null)
return;
if (clickedButton.ForeColor == Color.Black)
return;
if (firstClicked == null)
{
firstClicked = clickedButton;
firstClicked.ForeColor = Color.Black;
return;
}
secondClicked = clickedButton;
secondClicked.ForeColor = Color.Black;
CheckForWinner1();
if (firstClicked.Text == secondClicked.Text)
{
firstClicked = null;
secondClicked = null;
}
else
timer1.Start();
}
private void CheckForWinner1()
{
Button button;
for (int i = 0; i < tableLayoutPanel1.Controls.Count; i++)
{
button = tableLayoutPanel1.Controls[i] as Button;
if (button != null && button.ForeColor == button.BackColor)
return;
}
MessageBox.Show("Congratulations!");
}
private void Button_Click2(object sender, EventArgs e)
{
if (firstClicked != null && secondClicked != null)
return;
Button clickedButton = sender as Button;
if (clickedButton == null)
return;
if (clickedButton.ForeColor == Color.Black)
return;
if (firstClicked == null)
{
firstClicked = clickedButton;
firstClicked.ForeColor = Color.Black;
return;
}
secondClicked = clickedButton;
secondClicked.ForeColor = Color.Black;
CheckForWinner2();
if (firstClicked.Text == secondClicked.Text)
{
firstClicked = null;
secondClicked = null;
}
else
timer1.Start();
}
private void CheckForWinner2()
{
Button button;
for (int i = 0; i < tableLayoutPanel2.Controls.Count; i++)
{
button = tableLayoutPanel2.Controls[i] as Button;
if (button != null && button.ForeColor == button.BackColor)
return;
}
MessageBox.Show("Congratulations!");
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
firstClicked.ForeColor = firstClicked.BackColor;
secondClicked.ForeColor = secondClicked.BackColor;
firstClicked = null;
secondClicked = null;
}
I would suggest to use classes, so the task become trivial. Btw, since you are using winforms you can use "Tag" property to store a correct answer.
I built a small console app to highlight my idea:
using System;
using System.Collections.Generic;
namespace ConsoleApp9
{
public class GameObject
{
public int key { get; set; }
public string EN { get; set; }
public string FR { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<string> EngBasicPhrases = new List<string>()
{
"Hello", "How are you?", "Hot", "Thank you", "Welcome",
"Let's go", "My name is...", "Cold", "Good luck",
"Congratulations", "Bless you","I forgot","Sorry","I'm fine",
"It's no problem","Don't worry","Here it is","What?","Of course",
"Boy","Girl","Man","Woman","Friend","Almost","Late"
};
List<string> FrBasicPhrases = new List<string>()
{
"Salut","Ca va?","Chaud", "Merci", "Bienvenu", "Allons-y","Je m'appelle","Du froid",
"Bonne chance","Felicitations","A vos souhaits","J'ai oublie","Desole","Je vais bien",
"Ce n'est pas grave","Ne t'en fais pas","Voila","Comment?","Bien sur","Un garcon","Une fille",
"Un home","Une femme","Un ami","Presque","En retard"
};
List<GameObject> list = new List<GameObject>();
int max = EngBasicPhrases.Count;
for (int i = 0; i < max; i++)
{
list.Add(new GameObject { key = i, EN = EngBasicPhrases[i], FR = FrBasicPhrases[i] });
}
Random rnd = new Random();
int nextIndex = rnd.Next(max);
Console.WriteLine($"Guess this: { list[nextIndex].EN}");
Console.WriteLine($"Youe answer is (type number, press enter):");
for (int i = 0; i < max; i++)
{
Console.WriteLine($"{list[i].key} - { list[i].FR}");
}
int answer = int.Parse(Console.ReadLine());
if(nextIndex == answer)
{
Console.WriteLine($"you won a game !");
}
else
{
Console.WriteLine($"you lost a game ... the correct answer was {list[nextIndex].key} - {list[nextIndex].FR} ");
}
Console.WriteLine($"");
Console.WriteLine($"Game over");
Console.ReadKey();
}
}
}
I hope it helps 😊

Loop is not storing data in array correctly C#

Hey guys I'm currently working on a bank program for a class project. The idea the user will need to make an account if not done so already but if they already do they can just login using account number and pin. However. instead of my program constantly adding data to an array that's size is 100 it just replaces the data in slot [0] just wondering why.
public partial class Form1 : MetroForm
{
//For Creating new account
string newAccountType;
Accounts[] customers = new Accounts[99999];
int temp;
string VerifyPin = ("");
private void openAccount_Click(object sender, EventArgs e)
{
for (int index=0;index < customers.Length; ++index)
{
var R1 = new Random();
var R2 = new Random();
customers[index] = new Accounts();
customers[index].Name = newName.Text;
customers[index].accountType = newAccountType;
customers[index].accountNumber = (R1.Next(1000000,9000000))+(R2.Next(100,9000));
customers[index].accountPin = createPin.Text;
customers[index].accountBalance = 100.00;
temp = index;
}
MetroMessageBox.Show(this, "Thank you member "+customers[temp].Name+"\nYour member number is: "+customers[temp].accountNumber, "You are now a memeber", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
metroTabControl1.SelectedTab = metroTabPage2;
}
private void checkBalance_Click(object sender, EventArgs e)
{
int veri=0;
bool isfound = false;
for (int count = 0; count < customers.Length; ++count)
{
if (Convert.ToInt32(userName.Text) == customers[count].accountNumber)
{
veri = count;
isfound = true;
}
else
isfound = false;
accountnotfound.Text = "Account Not Found";
}
if (isfound && (customers[veri].accountPin == pinText.Text))
{
MetroMessageBox.Show(this, "account found", "account found");
}
else
{
MetroMessageBox.Show(this, "account not found or wrong pin", "account not found");
pinText.Text = "";
}
accountBalance.Visible = true;
userWithdraw.Visible = true;
userDeposite.Visible = true;
accountBalance.Text = "Welcome, "+customers[veri].Name+"\nYour current balance is: "+customers[veri].accountBalance;
}
public class Accounts
{
private string name, AccountType, AccountPin;
private int AccountNumber;
private double AccountBalance;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public int accountNumber
{
get
{
return AccountNumber;
}
set
{
AccountNumber = value;
}
}
public string accountPin
{
get
{
return AccountPin;
}
set
{
AccountPin = value;
}
}
public string accountType
{
get
{
return AccountType;
}
set
{
AccountType = value;
}
}
public double accountBalance
{
get
{
return AccountBalance;
}
set
{
AccountBalance = value;
}
}
}
I think you just need to keep track of which element in the array is available (i.e. has a null value). Once no elements in the array are null, this means that the customers array is full, so you can't add any more customers at that point.
Make these following changes. In the part of the code just where the code starts the loop:
bool added = false;
for (int index=0;index < customers.Length; ++index)
{
if (customers[index] != null) continue;
...
Also, after you actually add a customer, do this (right after the loop ends):
if (!added)
{
// show error message here!
}
else
{
MetroMessageBox.Show(this, "Thank you member "+customers[temp].Name+"\nYour member number is: "+customers[temp].accountNumber, "You are now a memeber", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
metroTabControl1.SelectedTab = metroTabPage2;
}
for (int index=0;index < customers.Length; ++index)
customers[index] = new Accounts();
Index will be 0 every time your array loops, thus replacing customers[0] every time you openAccount_Click is called.
You don't really need to loop to add. You just need to make sure you are writing the next possible index. Maybe use your Temp variable and increment it + 1 for every user added and then without a loop do like do.
customers[Temp] = new Accounts();
customers[Temp].Name = newName.Text;
customers[Temp].accountType = newAccountType;
customers[Temp].accountNumber = (R1.Next(1000000,9000000))+ (R2.Next(100,9000));
customers[Temp].accountPin = createPin.Text;
customers[Temp].accountBalance = 100.00;
Temp += 1;
You would be better off using a List of Accounts for your customers global instead.
List<Accounts> customers = new List<Accounts>();
Then inside openAccount_Click you can add a new Accounts like so.
customers.Add(new Accounts {
Name = newName.Text,
accountType = newAccountType,
accountNumber = (R1.Next(1000000,9000000))+(R2.Next(100,9000)),
accountPin = createPin.Text,
accountBalance = 100.00
});
bool added = false;
for (int x = 0; x <= temp; x++)
{
if (customers[temp] != null) continue;
{
for (int indexies = 0; indexies < customers.Length; indexies++)
{
var R1 = new Random();
var R2 = new Random();
Convert.ToInt32(createPin.Text);
customers[temp] = new Accounts();
customers[temp].Name = newName.Text;
customers[temp].accountType = newAccountType;
customers[temp].accountNumber = 1;//(R1.Next(1000000, 9000000)) + (R2.Next(100, 9000));
customers[temp].accountPin = Convert.ToInt32(createPin.Text);
customers[temp].accountBalance = 100.00;
added = true;
}
}
}

How to get selected value or index of a dropdownlist upon entering a page?

I have a product ordering page with various product option dropdownlists which are inside a repeater. The "Add To Cart" button is "inactive" until all the options have a selection. Technically, the "Add To Cart" button has two images: a grey one which is used when the user has not selected choices for all options available to a product and an orange one which is used when the user has made a selection from each dropdownlist field.These images are set by the ShowAddToBasket and HideAddToBasket functions.
The dropdownlist fields are connected in that a selection from the first field will determine a selection for the second and sometimes third field. If the second field is NOT pre-set by the first field, then the second field will determine the value for the third field. The first dropdownlist field is never disabled, but the other two can be based on what options have been selected.
There are a few products that have all 3 of their dropdownlists pre-set to certain choices upon entering their page. This means they are all disabled and cannot be changed by the user. Regardless of whether the user enters in a quantity or not, the "Add To Cart" button NEVER activates. I cannot for the life of me figure out how to change it so that, in these rare circumstances, the "Add to Cart" button is automatically set to active once a quantity has been entered. The dropdownlists still have options selected in these pages--it's just that they are fixed and cannot be changed by the user.
Is there anyway I can get the selected value or selected index of these dropdownlist fields upon entering a product page? I want to be able to check to see if they are truly "empty" or if they do have selections made so I can set the "Add to Cart" button accordingly.
Any help would be great because I'm really stuck on this one! :(
Here is the code behind (I removed a lot of the unimportant functions):
protected void Page_Init(object sender, System.EventArgs e)
{
string MyPath = HttpContext.Current.Request.Url.AbsolutePath;
MyPath = MyPath.ToLower();
_Basket = AbleContext.Current.User.Basket;
RedirQryStr = "";
_ProductId = AlwaysConvert.ToInt(Request.QueryString["ProductId"]);
if (Request.QueryString["LineID"] != null)
{
int LineID = Convert.ToInt32(Request.QueryString["LineID"].ToString());
int itemIndex = _Basket.Items.IndexOf(LineID);
BasketItem item = _Basket.Items[itemIndex];
OldWeight.Text = item.Weight.ToString();
OldQty.Text = item.Quantity.ToString();
OldPrice.Text = item.Price.ToString();
}
int UnitMeasure = 0;
SetBaidCustoms(ref UnitMeasure);
GetPrefinishNote();
_ProductId = AlwaysConvert.ToInt(Request.QueryString["ProductId"]);
_Product = ProductDataSource.Load(_ProductId);
if (_Product != null)
{
//GetPercentage();
int _PieceCount = 0;
double _SurchargePercent = 0;
CheckoutHelper.GetItemSurcargePercent(_Product, ref _PieceCount, ref _SurchargePercent);
SurchargePieceCount.Text = _PieceCount.ToString();
SurchargePercent.Text = _SurchargePercent.ToString();
//add weight
BaseWeight.Value = _Product.Weight.ToString();
//DISABLE PURCHASE CONTROLS BY DEFAULT
AddToBasketButton.Visible = false;
rowQuantity.Visible = false;
//HANDLE SKU ROW
trSku.Visible = (ShowSku && (_Product.Sku != string.Empty));
if (trSku.Visible)
{
Sku.Text = _Product.Sku;
}
//HANDLE PART/MODEL NUMBER ROW
trPartNumber.Visible = (ShowPartNumber && (_Product.ModelNumber != string.Empty));
if (trPartNumber.Visible)
{
PartNumber.Text = _Product.ModelNumber;
}
//HANDLE REGPRICE ROW
if (ShowMSRP)
{
decimal msrpWithVAT = TaxHelper.GetShopPrice(_Product.MSRP, _Product.TaxCode != null ? _Product.TaxCode.Id : 0);
if (msrpWithVAT > 0)
{
trRegPrice.Visible = true;
RegPrice.Text = msrpWithVAT.LSCurrencyFormat("ulc");
}
else trRegPrice.Visible = false;
}
else trRegPrice.Visible = false;
// HANDLE PRICES VISIBILITY
if (ShowPrice)
{
if (!_Product.UseVariablePrice)
{
trBasePrice.Visible = true;
BasePrice.Text = _Product.Price.ToString("F2") + BairdLookUp.UnitOfMeasure(UnitMeasure);
trOurPrice.Visible = true;
trVariablePrice.Visible = false;
}
else
{
trOurPrice.Visible = false;
trVariablePrice.Visible = true;
VariablePrice.Text = _Product.Price.ToString("F2");
string varPriceText = string.Empty;
Currency userCurrency = AbleContext.Current.User.UserCurrency;
decimal userLocalMinimum = userCurrency.ConvertFromBase(_Product.MinimumPrice.HasValue ? _Product.MinimumPrice.Value : 0);
decimal userLocalMaximum = userCurrency.ConvertFromBase(_Product.MaximumPrice.HasValue ? _Product.MaximumPrice.Value : 0);
if (userLocalMinimum > 0)
{
if (userLocalMaximum > 0)
{
varPriceText = string.Format("(between {0} and {1})", userLocalMinimum.LSCurrencyFormat("ulcf"), userLocalMaximum.LSCurrencyFormat("ulcf"));
}
else
{
varPriceText = string.Format("(at least {0})", userLocalMinimum.LSCurrencyFormat("ulcf"));
}
}
else if (userLocalMaximum > 0)
{
varPriceText = string.Format("({0} maximum)", userLocalMaximum.LSCurrencyFormat("ulcf"));
}
phVariablePrice.Controls.Add(new LiteralControl(varPriceText));
}
}
//UPDATE QUANTITY LIMITS
if ((_Product.MinQuantity > 0) && (_Product.MaxQuantity > 0))
{
string format = " (min {0}, max {1})";
QuantityLimitsPanel.Controls.Add(new LiteralControl(string.Format(format, _Product.MinQuantity, _Product.MaxQuantity)));
QuantityX.MinValue = _Product.MinQuantity;
QuantityX.MaxValue = _Product.MaxQuantity;
}
else if (_Product.MinQuantity > 0)
{
string format = " (min {0})";
QuantityLimitsPanel.Controls.Add(new LiteralControl(string.Format(format, _Product.MinQuantity)));
QuantityX.MinValue = _Product.MinQuantity;
}
else if (_Product.MaxQuantity > 0)
{
string format = " (max {0})";
QuantityLimitsPanel.Controls.Add(new LiteralControl(string.Format(format, _Product.MaxQuantity)));
QuantityX.MaxValue = _Product.MaxQuantity;
}
if (QuantityX.MinValue > 0) QuantityX.Text = QuantityX.MinValue.ToString();
AddToWishlistButton.Visible = AbleContext.Current.StoreMode == StoreMode.Standard;
}
else
{
this.Controls.Clear();
}
if (!Page.IsPostBack)
{
if (Request.QueryString["Action"] != null)
{
if (Request.QueryString["Action"].ToString().ToLower() == "edit")
{
SetEdit();
}
}
}
}
protected void Page_Load(object sender, System.EventArgs e)
{
if (_Product != null)
{
if (ViewState["OptionDropDownIds"] != null)
{
_OptionDropDownIds = (Hashtable)ViewState["OptionDropDownIds"];
}
else
{
_OptionDropDownIds = new Hashtable();
}
if (ViewState["OptionPickerIds"] != null)
{
_OptionPickerIds = (Hashtable)ViewState["OptionPickerIds"];
}
else
{
_OptionPickerIds = new Hashtable();
}
_SelectedOptionChoices = GetSelectedOptionChoices();
OptionsList.DataSource = GetProductOptions();
OptionsList.DataBind();
//set all to the first value
foreach (RepeaterItem rptItem in OptionsList.Items)
{
DropDownList OptionChoices = (DropDownList)rptItem.FindControl("OptionChoices");
OptionChoices.SelectedIndex = 1;
}
TemplatesList.DataSource = GetProductTemplateFields();
TemplatesList.DataBind();
KitsList.DataSource = GetProductKitComponents();
KitsList.DataBind();
}
if (!Page.IsPostBack)
{
if (_Product.MSRP != 0)
{
salePrice.Visible = true;
RetailPrice.Text = _Product.MSRP.ToString("$0.00");
}
DataSet ds = new DataSet();
DataTable ResultTable = ds.Tables.Add("CatTable");
ResultTable.Columns.Add("OptionID", Type.GetType("System.String"));
ResultTable.Columns.Add("OptionName", Type.GetType("System.String"));
ResultTable.Columns.Add("LinkHeader", Type.GetType("System.String"));
foreach (ProductOption PhOpt in _Product.ProductOptions)
{
string MasterList = GetProductMaster(_ProductId, PhOpt.OptionId);
string PerFootVal = "";
string LinkHeader = "";
string DefaultOption = "no";
string PrefinishMin = "0";
bool VisPlaceholder = true;
ProductDisplayHelper.TestForVariantDependency(ref SlaveHide, _ProductId, PhOpt, ref PrefinishMin, ref PerFootVal, ref LinkHeader, ref VisPlaceholder, ref HasDefault, ref DefaultOption);
if (PrefinishMin == "")
PrefinishMin = "0";
DataRow dr = ResultTable.NewRow();
dr["OptionID"] = PhOpt.OptionId + ":" + MasterList + ":" + PerFootVal + ":" + DefaultOption + ":" + PrefinishMin;
Option _Option = OptionDataSource.Load(PhOpt.OptionId);
dr["OptionName"] = _Option.Name;
dr["LinkHeader"] = LinkHeader;
ResultTable.Rows.Add(dr);
}
//Bind the data to the Repeater
ItemOptions.DataSource = ds;
ItemOptions.DataMember = "CatTable";
ItemOptions.DataBind();
//determine if buttons show
if (ItemOptions.Items.Count == 0)
{
ShowAddToBasket(1);
resetBtn.Visible = true;
}
else
{
HideAddToBasket(3);
}
if (Request.QueryString["Action"] != null)
{
ShowAddToBasket(1);
SetDllAssociation(false);
}
ShowHideDrops();
}
}
private void HideAddToBasket(int Location)
{
AddToBasketButton.Visible = false;
AddToWishlistButton.Visible = false;
resetBtn.Visible = false;
if (Request.QueryString["Action"] == null)
{
SelectAll.Visible = true;
WishGray.Visible = true;
if (Request.QueryString["OrderItemID"] == null)
BasketGray.Visible = true;
else
UpdateButton.Visible = false;
}
else
{
UpdateButton.Visible = true;
NewButtons.Visible = false;
}
if ((_Product.MinQuantity == 1) & (_Product.MaxQuantity == 1))
{
AddToWishlistButton.Visible = false;
BasketGray.Visible = false;
}
}
private void ShowAddToBasket(int place)
{
resetBtn.Visible = true;
if (Request.QueryString["Action"] != null)
{
UpdateButton.Visible = true;
NewButtons.Visible = false;
}
else
{
UpdateButton.Visible = false;
SelectAll.Visible = false;
WishGray.Visible = false;
BasketGray.Visible = false;
if (Request.QueryString["OrderItemID"] == null)
{
AddToBasketButton.Visible = true;
resetBtn.Visible = true;
AddToWishlistButton.Visible = true;
}
else
{
UpdateButton.Visible = true;
AddToBasketButton.Visible = false;
}
}
if ((_Product.MinQuantity == 1) & (_Product.MaxQuantity == 1))
{
AddToWishlistButton.Visible = false;
BasketGray.Visible = false;
resetBtn.Visible = true;
}
}
protected void OptionChoices_DataBound(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
if (ddl != null)
{
//bb5.Text = "ddl !=null<br />"; works
List<OptionChoiceItem> ds = (List<OptionChoiceItem>)ddl.DataSource;
if (ds != null && ds.Count > 0)
{
int optionId = ds[0].OptionId;
Option opt = OptionDataSource.Load(optionId);
ShowAddToBasket(4);
OptionChoiceItem oci = ds.FirstOrDefault<OptionChoiceItem>(c => c.Selected);
if (oci != null)
{
ListItem item = ddl.Items.FindByValue(oci.ChoiceId.ToString());
if (item != null)
{
ddl.ClearSelection();
item.Selected = true;
}
}
if (opt != null && !opt.ShowThumbnails)
{
if (!_OptionDropDownIds.Contains(optionId))
{
// bb5.Text = "!_OptionDropDownIds.Contains(optionId)<br />"; works
_OptionDropDownIds.Add(optionId, ddl.UniqueID);
}
if (_SelectedOptionChoices.ContainsKey(optionId))
{
ListItem selectedItem = ddl.Items.FindByValue(_SelectedOptionChoices[optionId].ToString());
if (selectedItem != null)
{
ddl.ClearSelection();
selectedItem.Selected = true;
//bb5.Text = "true: " + selectedItem.Selected.ToString()+"<br />"; doesn't work
}
}
StringBuilder imageScript = new StringBuilder();
imageScript.Append("<script type=\"text/javascript\">\n");
imageScript.Append(" var " + ddl.ClientID + "_Images = {};\n");
foreach (OptionChoice choice in opt.Choices)
{
if (!string.IsNullOrEmpty(choice.ImageUrl))
{
imageScript.Append(" " + ddl.ClientID + "_Images[" + choice.Id.ToString() + "] = '" + this.Page.ResolveUrl(choice.ImageUrl) + "';\n");
}
}
imageScript.Append("</script>\n");
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
if (scriptManager != null)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), ddl.ClientID, imageScript.ToString(), false);
}
else
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), ddl.ClientID, imageScript.ToString());
}
}
}
ddl.Attributes.Add("onChange", "OptionSelectionChanged('" + ddl.ClientID + "');");
}
}
protected Dictionary<int, int> GetSelectedOptionChoices()
{
HttpRequest request = HttpContext.Current.Request;
Dictionary<int, int> selectedChoices = new Dictionary<int, int>();
if (Page.IsPostBack)
{
foreach (int key in _OptionDropDownIds.Keys)
{
string value = (string)_OptionDropDownIds[key];
Trace.Write(string.Format("Checking For - OptionId:{0} DropDownId:{1}", key, value));
string selectedChoice = request.Form[value];
if (!string.IsNullOrEmpty(selectedChoice))
{
int choiceId = AlwaysConvert.ToInt(selectedChoice);
if (choiceId != 0)
{
Trace.Write(string.Format("Found Selected Choice : {0} - {1}", key, choiceId));
selectedChoices.Add(key, choiceId);
}
}
}
foreach (int key in _OptionPickerIds.Keys)
{
string value = (string)_OptionPickerIds[key];
Trace.Write(string.Format("Checking For - OptionId:{0} PickerId:{1}", key, value));
string selectedChoice = request.Form[value];
if (!string.IsNullOrEmpty(selectedChoice))
{
int choiceId = AlwaysConvert.ToInt(selectedChoice);
if (choiceId != 0)
{
Trace.Write(string.Format("Found Selected Choice : {0} - {1}", key, choiceId));
selectedChoices.Add(key, choiceId);
}
}
}
}
else
{
string optionList = Request.QueryString["Options"];
ShowAddToBasket(2);
if (!string.IsNullOrEmpty(optionList))
{
string[] optionChoices = optionList.Split(',');
if (optionChoices != null)
{
foreach (string optionChoice in optionChoices)
{
OptionChoice choice = OptionChoiceDataSource.Load(AlwaysConvert.ToInt(optionChoice));
if (choice != null)
{
_SelectedOptionChoices.Add(choice.OptionId, choice.Id);
}
}
return _SelectedOptionChoices;
}
}
}
return selectedChoices;
}
protected void SetDDLs(object sender, EventArgs e)
{
bool isRandom = false;
if (LengthDDL.Text != "")
isRandom = true;
SetDllAssociation(isRandom);
}
Try accessing the values in the Page_Load event. I don't believe the values are bound yet in Page_Init

Categories