How would i optimise this if statement - c#

Im finally done with my project and im going through my code and optimising it and trying to cut down on the chunky lines of code, how would i optimize this, it a series of if statments that matches text and adds value to a corresponding text box
private void btnfinalize_Click(object sender, EventArgs e)
{
//Daily Sales
for (int i = 0; i < POSDGV.Rows.Count; ++i)
{
if (POSDGV.Rows[i].Cells[0].Value.ToString() == "Manga vol 1-5 ")
{
var Book1 = Int32.Parse(POSDGV.Rows[i].Cells[1].Value.ToString());
Global.Book1 = Book1 + Global.Book1;
}
else if (POSDGV.Rows[i].Cells[0].Value.ToString() == "Manga vol 6-15 ")
{
var Book2 = Int32.Parse(POSDGV.Rows[i].Cells[1].Value.ToString());
Global.Book2 = Book2 + Global.Book2;
}
else if (POSDGV.Rows[i].Cells[0].Value.ToString() == "Novels 1-199 ")
{
var Book3 = Int32.Parse(POSDGV.Rows[i].Cells[1].Value.ToString());
Global.Book3 = Book3 + Global.Book3;
}
else if (POSDGV.Rows[i].Cells[0].Value.ToString() == "Novels 200-400 ")
{
var Book4 = Int32.Parse(POSDGV.Rows[i].Cells[1].Value.ToString());
Global.Book4 = Book4 + Global.Book4;
}
else if (POSDGV.Rows[i].Cells[0].Value.ToString() == "Comics series mainstream ")
{
var Book5 = Int32.Parse(POSDGV.Rows[i].Cells[1].Value.ToString());
Global.Book5 = Book5 + Global.Book5;
}
else if (POSDGV.Rows[i].Cells[0].Value.ToString() == "Comics series secondary ")
{
var Book6 = Int32.Parse(POSDGV.Rows[i].Cells[1].Value.ToString());
Global.Book6 = Book6 + Global.Book6;
}
else if (POSDGV.Rows[i].Cells[0].Value.ToString() == "Text book 1 semester/2 modules ")
{
var Book7 = Int32.Parse(POSDGV.Rows[i].Cells[1].Value.ToString());
Global.Book7 = Book7 + Global.Book7;
}
else if (POSDGV.Rows[i].Cells[0].Value.ToString() == "Text book module add-ons ")
{
var Book8 = Int32.Parse(POSDGV.Rows[i].Cells[1].Value.ToString());
Global.Book8 = Book8 + Global.Book8;
}
else if (POSDGV.Rows[i].Cells[0].Value.ToString() == "Hardcover ")
{
var Hardcover = Int32.Parse(POSDGV.Rows[i].Cells[1].Value.ToString());
Global.Hardcover = Hardcover + Global.Hardcover;
}
}
thx for the help

By using a dictionary:
var actions = new Dictionary<string, Action<int>>
{
["Manga vol 1-5 "] = book => Global.Book1 += book,
["Manga vol 6-15 "] = book => Global.Book2 += book
//...
};
Then:
for (int i = 0; i < POSDGV.Rows.Count; ++i)
{
var book = Int32.Parse(POSDGV.Rows[i].Cells[1].Value.ToString());
var action = actions[POSDGV.Rows[i].Cells[0].Value.ToString()];
action(book);
}
Or using a foreach loop:
foreach (var row in POSDGV.Rows)
{
var book = Int32.Parse(row.Cells[1].Value.ToString());
var action = actions[row.Cells[0].Value.ToString()];
action(book);
}

You can also use switch with strings
private void btnfinalize_Click(object sender, EventArgs e)
{
//Daily Sales
for (int i = 0; i < POSDGV.Rows.Count; ++i)
{
var value = POSDGV.Rows[i].Cells[0].Value.ToString();
var book = Int32.Parse(POSDGV.Rows[i].Cells[1].Value.ToString());
switch (value)
{
case "Manga vol 1-5 ":
{
Global.Book1 = Book + Global.Book1;
break;
}
//other cases
}
}
}
Using foreach makes it much more readable
private void btnfinalize_Click(object sender, EventArgs e)
{
//Daily Sales
foreach (var row in POSDGV.Rows)
{
var value = row.Cells[0].Value.ToString();
var book = Int32.Parse(row.Cells[1].Value.ToString());
switch (value)
{
case "Manga vol 1-5 ":
{
Global.Book1 = Book + Global.Book1;
break;
}
//other cases
}
}
}

private void btnfinalize_Click(object sender, EventArgs e)
{
//Daily Sales
for (int i = 0; i < POSDGV.Rows.Count; ++i)
{
string str1 = POSDGV.Rows[i].Cells[0].Value.ToString();
string str2 = POSDGV.Rows[i].Cells[1].Value.ToString();
var Book = Int32.Parse(str2);
if (str1 == "Manga vol 1-5 ")
{
Global.Book1 = Book + Global.Book1;
}
else if (str1 == "Manga vol 6-15 ")
{
Global.Book2 = Book + Global.Book2;
}
else if (str1 == "Novels 1-199 ")
{
Global.Book3 = Book + Global.Book3;
}
else if (str1 == "Novels 200-400 ")
{
Global.Book4 = Book + Global.Book4;
}
else if (str1 == "Comics series mainstream ")
{
Global.Book5 = Book + Global.Book5;
}
else if (str1 == "Comics series secondary ")
{
Global.Book6 = Book + Global.Book6;
}
else if (str1 == "Text book 1 semester/2 modules ")
{
Global.Book7 = Book + Global.Book7;
}
else if (str1 == "Text book module add-ons ")
{
Global.Book8 = Book + Global.Book8;
}
else if (str1 == "Hardcover ")
{
var Hardcover = Int32.Parse(str2);
Global.Hardcover = Hardcover + Global.Hardcover;
}
}
}
Using a variable will lessen the characters in a code. You can also try using enumerations so you can use switch-case.

Related

Return two collections in one

how can i add collection to another collection? I am returnging one collection _lastOpenedArticles and if that collection has less than 3 articles i need to add articles from allUsersArticles. However i keep getting article from collection _lastOpenedArticles 3 times. Can you help please.
async Task ShowLastListenedAsync(List<Article> allUserArticles)
{
var downloadedArticles = LangUpDataSaverLoader.DeserializeAllOptimizationData();
if (_lastOpenedArticles != null && _lastOpenedArticles.Count > 0)
{
foreach (var article in _lastOpenedArticles.Take(3))
{
var filename = string.Format(SharedConstants.ArticleImageUrl, SharedConstants.ApiBaseUri, article.Id);
var newCell = new ArticleDetailData()
{
Author = article.Author,
Id = article.Id,
};
if (downloadedArticles.DownloadedArticles.Any(m => m.Id == article.Id))
{
newCell.BackgroundImage = article.Id.ArticleImageFile();
}
else
{
newCell.BackgroundImage = filename;
}
var sec = article.Category;
if (sec == null)
{
newCell.Section = " ";
}
else
{
newCell.Section = article.Category;
}
LastThreeArticles.Add(newCell);
if (_lastOpenedArticles.Count < 3)
{
foreach (var art in allUserArticles.Take(3))
{
filename = string.Format(SharedConstants.ArticleImageUrl, SharedConstants.ApiBaseUri, article.Id);
var cell = new ArticleDetailData()
{
Author = article.Author,
BackgroundImage = filename,
Id = article.Id,
};
sec = article.Category;
if (sec == null)
{
cell.Section = " ";
}
else
{
cell.Section = article.Category;
}
LastThreeArticles.Add(cell);
}
await FillAnonymousArticles(allUserArticles);
}
}
}
else
{
await FillAnonymousArticles(allUserArticles);
}
}
Instead of checking the count in the for loop, I'd propose to move the check whether you already have 3 articles after the loop. So you avoid to get the articles 3 times (once for each run of the loop):
async Task ShowLastListenedAsync(List<Article> allUserArticles)
{
var downloadedArticles = LangUpDataSaverLoader.DeserializeAllOptimizationData();
if (_lastOpenedArticles != null && _lastOpenedArticles.Count > 0)
{
foreach (var article in _lastOpenedArticles.Take(3))
{
var filename = string.Format(SharedConstants.ArticleImageUrl, SharedConstants.ApiBaseUri, article.Id);
var newCell = new ArticleDetailData()
{
Author = article.Author,
Id = article.Id,
};
if (downloadedArticles.DownloadedArticles.Any(m => m.Id == article.Id))
{
newCell.BackgroundImage = article.Id.ArticleImageFile();
}
else
{
newCell.BackgroundImage = filename;
}
var sec = article.Category;
if (sec == null)
{
newCell.Section = " ";
}
else
{
newCell.Section = article.Category;
}
LastThreeArticles.Add(newCell);
}
// Move this check out of the for loop
if (_lastOpenedArticles.Count < 3)
{
foreach (var art in allUserArticles.Take(3))
{
filename = string.Format(SharedConstants.ArticleImageUrl, SharedConstants.ApiBaseUri, article.Id);
var cell = new ArticleDetailData()
{
Author = article.Author,
BackgroundImage = filename,
Id = article.Id,
};
sec = article.Category;
if (sec == null)
{
cell.Section = " ";
}
else
{
cell.Section = article.Category;
}
LastThreeArticles.Add(cell);
}
await FillAnonymousArticles(allUserArticles);
}
}
else
{
await FillAnonymousArticles(allUserArticles);
}
}
In addition, you could use Linq to create a union of the lists. This will result in much shorter code, for example:
_lastOpenedArticles
.Union(allUserArticles)
.Take(3)
.Select(x => ConvertToCell(x)) // You need this method that converts the articles to a cell
.ToArray(); // If you need a list, you can also use ToList()
_lastOpenedArticles.AddRange(allUserArticles)
_lastOpenedArticles.Concat(allUserArticles)
the last one returns IEnumerable<T> and first one is void. Take one that suits you better

How to call function randomly in c# according to checkbox list selection value?

Checkbox List has n items, then combination of selection of items has various logic.
e.g. 4 items in list, then user can select 1, 2 ,3 or 4 items.
when 1 items selected possible case is 4
->if items[0] selected then (random_function[0])
->if items1 selected then (random_function1)
.
.so on
when 2 items selected possible case is 6
->if items[0] & items1 then select (random_function[0] or random_function1)
->if items[0] & items[2] then select (random_function[0] or random_function[2])
.
.so on
when 3 items selected possible case is 3
->if items[0] & items1 & items[2] then select (random_function[0] or random_function1 or random_function[2])
->if items[0] & items1 & items[3] then select (random_function[0] or random_function1 or random_function[3])
.
.so on
when 4 items selected possible case is 1
->if items[0] & items1 & items[2] & items[4] then select (random_function[0] or random_function1 or random_function[2] or random_function[3])
Note.: random_function[i] call randomly
so, each items has each if cases,
it is possible for small number of n, what if value of n is greater than 10 or 20.
I tried for n=4 (checklistbox items) but i have to try for n=15.
How to call these function according items selected combinations.
And following code in button click event:
`
string s = null;
int c = 0;
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if (checkedListBox1.GetItemChecked(i))
{
c = c + 1;
}
}
if (c == 1)
{
if (checkedListBox1.GetItemChecked(0))
{ s = " Item one"; }
else if (checkedListBox1.GetItemChecked(1))
{ s = " Item two "; }
else if (checkedListBox1.GetItemChecked(2))
{ s = " Item three "; }
else if (checkedListBox1.GetItemChecked(3))
{ s = " Item four "; }
}
else if (c == 2)
{
Random r = new Random();
int var = r.Next(1, 3);
if (checkedListBox1.GetItemChecked(0) && checkedListBox1.GetItemChecked(1))
{
if (var == 1) { s = " Item one "; }
else { s = " Item two "; }
}
else if (checkedListBox1.GetItemChecked(0) && checkedListBox1.GetItemChecked(2))
{
if (var == 1) { s = " Item one "; }
else { s = " Item three "; }
}
else if (checkedListBox1.GetItemChecked(0) && checkedListBox1.GetItemChecked(3))
{
if (var == 1) { s = " Item one "; }
else { s = " Item four "; }
}
else if (checkedListBox1.GetItemChecked(1) && checkedListBox1.GetItemChecked(2))
{
if (var == 1) { s = " Item two "; }
else { s = " Item three "; }
}
else if (checkedListBox1.GetItemChecked(1) && checkedListBox1.GetItemChecked(3))
{
if (var == 1) { s = " Item two "; }
else { s = " Item four "; }
}
else if (checkedListBox1.GetItemChecked(2) && checkedListBox1.GetItemChecked(3))
{
if (var == 1) { s = " Item three "; }
else { s = " Item four "; }
}
}
else if (c == 3)
{
Random r = new Random();
int var = r.Next(1, 4);
if (checkedListBox1.GetItemChecked(0) && checkedListBox1.GetItemChecked(1) && checkedListBox1.GetItemChecked(2))
{
if (var == 1) { s = " Item one "; }
else if (var == 2) { s = " Item two "; }
else { s = " Item three "; }
}
else if (checkedListBox1.GetItemChecked(0) && checkedListBox1.GetItemChecked(1) && checkedListBox1.GetItemChecked(3))
{
if (var == 1) { s = " Item one "; }
else if (var == 2) { s = " Item two "; }
else { s = " Item three "; }
}
else if (checkedListBox1.GetItemChecked(1) && checkedListBox1.GetItemChecked(2) && checkedListBox1.GetItemChecked(3))
{
if (var == 1) { s = " Item one "; }
else if (var == 2) { s = " Item two "; }
else { s = " Item three "; }
}
}
else if (c == 4)
{
Random r = new Random();
int var = r.Next(1, 4);
if (checkedListBox1.GetItemChecked(0) && checkedListBox1.GetItemChecked(1) && checkedListBox1.GetItemChecked(2) && checkedListBox1.GetItemChecked(3))
{
if (var == 1) { s = " Item one "; }
else if (var == 2) { s = " Item two "; }
else if (var == 3) { s = " Item three "; }
else { s = " Item four "; }
}
}
label1.Text = s; //output
`

Finding longest time in an array

I have an array of phrases, like
"6 days, 7 months, 2 years"
and I need to go through the array to find the longest time and return that value. I've built something to insert into my application as a custom action but it crashes my application. It does not generate an error message.
bool booDayFound = false;
bool booMonthFound = false;
bool booYearFound = false;
string DayPrognosisLength = null;
string MonthPrognosisLength = null;
string YearPrognosisLength = null;
string strOutValue = null;
int LongestDayLength = 0;
int LongestMonthLength = 0;
int LongestYearLength = 0;
string[] arrDayLength = null;
string[] arrMonthLength = null;
string[] arrYearLength = null;
string strPrognosis = Extracted_Prognosis;
char charSeperator = ',';
String[] arrPrognosis = strPrognosis.Split(charSeperator);
foreach (var varPrognosis in arrPrognosis)
if (varPrognosis.Contains("Day") || varPrognosis.Contains("Days") || varPrognosis.Contains("day") || varPrognosis.Contains("days"))
{
booDayFound = true;
DayPrognosisLength = Regex.Replace(varPrognosis, "[^0-9]", "");
DayPrognosisLength = DayPrognosisLength + ",";
arrDayLength = DayPrognosisLength.Split(',');
LongestDayLength = arrDayLength.Max(c => int.Parse(c));
}
else
{
booDayFound = false;
DayPrognosisLength = "";
}
foreach (var varPrognosis in arrPrognosis)
if (varPrognosis.Contains("Months") || varPrognosis.Contains("Month") || varPrognosis.Contains("months") || varPrognosis.Contains("month"))
{
booMonthFound = true;
MonthPrognosisLength = Regex.Replace(varPrognosis, "[^0-9]", "");
MonthPrognosisLength = MonthPrognosisLength + ",";
arrMonthLength = MonthPrognosisLength.Split(',');
LongestMonthLength = arrMonthLength.Max(c => int.Parse(c));
}
else
{
booMonthFound = false;
MonthPrognosisLength = "";
}
foreach (var varPrognosis in arrPrognosis)
if (varPrognosis.Contains("Year") || varPrognosis.Contains("Years") || varPrognosis.Contains("year") || varPrognosis.Contains("years"))
{
booYearFound = true;
YearPrognosisLength = Regex.Replace(varPrognosis, "[^0-9]", "");
YearPrognosisLength = YearPrognosisLength + ",";
arrYearLength = YearPrognosisLength.Split(',');
LongestYearLength = arrYearLength.Max(c => int.Parse(c));
}
else
{
booYearFound = false;
YearPrognosisLength = "";
}
if (booYearFound == true)
{
strOutValue = "Year:" + LongestYearLength.ToString();
localsmartobj.DCONavSetValue(ExtractedPrognosisLocation, strOutValue);
AdmiralLog("Longest prognosis length is " + LongestYearLength.ToString() + "Years(s)");
}
else if (booMonthFound == true)
{
strOutValue = "Month:" + LongestMonthLength.ToString();
localsmartobj.DCONavSetValue(ExtractedPrognosisLocation, strOutValue);
AdmiralLog("Longest prognosis length is " + LongestMonthLength.ToString() + "Month(s)");
}
else if (booDayFound == true)
{
strOutValue = "Day:" + LongestDayLength.ToString();
localsmartobj.DCONavSetValue(ExtractedPrognosisLocation, strOutValue);
AdmiralLog("Longest prognosis length is " + LongestDayLength.ToString() + "Day(s)");
}
return true;
}
catch (Exception ex)
{
AdmiralLog(ex.Message);
return false;
}
}
I've trimmed some Datacap specific functions and I know that my code is not the cleanest but I would like to know what am I missing here?
First, we have to come to terms: let's assume that
1 month == 30 days
1 year == 365 days
Then we can implement Duration function: given a string return duration in days:
Func<string, string, int> DurationTerm = (src, mask) => Regex
.Matches(
src,
$#"(?<number>[0-9]+)\s*{mask.TrimEnd('s', 'S')}s?",
RegexOptions.IgnoreCase)
.Cast<Match>()
.Select(match => int.Parse(match.Groups["number"].Value))
.DefaultIfEmpty()
.Sum();
//TODO: I've assumed 1 Month == 30 days, 1 Year == 365 days
// Correct the logic if required
Func<string, int> Duration = (src) =>
DurationTerm(src, "day") +
// DurationTerm(src, "week") * 7 + //TODO: Add more terms if you want
DurationTerm(src, "month") * 30 +
DurationTerm(src, "year") * 365;
Now we are ready to find out the longest time:
using System.Linq;
...
string[] arrPrognosis = ...
int LongestDayLength = arrPrognosis
.Max(item => Duration(item));

Excel takes only that no of rows which has data in c#...my code works for some excel sheet not for all

Excel sheets made by different different clients...that code works when i make but not when user make..is anything problem with excel sheet so , i can tell user make like that way..or i can do anything with my code.
private void MeterUpdateByExcelSheet(HttpPostedFileBase file)
{
List<string> errorMessages = new List<string>();
int siteId = Helpers.SiteHelpers.Functions.GetSiteIdOfLoginUser().Value;
var stream = file.InputStream;
using (var package = new ExcelPackage(stream))
{
//getting number of sheets
var sheets = package.Workbook.Worksheets;
int totalProcessedMeters = 0;
if (sheets.Count > 0)
{
var sheet = sheets.FirstOrDefault();
//getting number of rows
var rows = sheet.Dimension.End.Row;
for (int row = 2; row <= rows; row++)
{
//get data for a row from excel
var meterNo = Convert.ToString(sheet.Cells[row, 1].Value);
int? sanctionLoadMains = (int)Convert.ToDecimal(sheet.Cells[row, 2].Value);
int? sanctionLoadDG = (int)Convert.ToDecimal(sheet.Cells[row, 3].Value);
int? unitArea = (int)Convert.ToDecimal(sheet.Cells[row, 4].Value);
int? creditLimit = (int)Convert.ToDecimal(sheet.Cells[row, 5].Value);
int? sMSWarning = (int)Convert.ToDecimal(sheet.Cells[row, 6].Value);
int? sMSWarning1 = (int)Convert.ToDecimal(sheet.Cells[row, 7].Value);
string date = sheet.Cells[row, 8].Value.ToString();
DateTime billingDate;
if (string.IsNullOrEmpty(date))
{
errorMessages.Add("Date is not given for MeterNo " + meterNo + " at row " + row);
continue;
}
if (!DateTime.TryParseExact(date, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out billingDate))
{
errorMessages.Add("Date format is not correct for MeterNo. " + meterNo + " at row " + row);
continue;
}
if (!string.IsNullOrEmpty(meterNo))
{
meterNo = meterNo.PadLeft(9, '0');
var oldMeter = _meterRepository.GetBySiteIdAndMeterNo(siteId, meterNo);
var newMeter = _meterRepository.GetBySiteIdAndMeterNo(siteId, meterNo);
int wattUnit = 1000;//loads should be multiple of 1000(watt)
int smsWarningUnit = 100;//sms warnings should be multiple of 100
if (newMeter == null)
{
errorMessages.Add("MeterNo. " + meterNo + " does not exist.");
continue;
}
if (sanctionLoadMains.HasValue && sanctionLoadMains >= 500)
{
newMeter.LoadSenctionMain = sanctionLoadMains.Value;
}
if (sanctionLoadDG.HasValue && sanctionLoadDG >= 500)
{
newMeter.LoadSenctionDG = sanctionLoadDG.Value;
}
if (unitArea.HasValue)
{
newMeter.UnitArea = unitArea.Value;
}
if (creditLimit.HasValue)
{
newMeter.CreditLimit = creditLimit.Value;
}
if (sMSWarning.HasValue && sMSWarning >= 100)
{
newMeter.SMSWarningAmount = sMSWarning.Value;
}
if (sMSWarning1.HasValue && sMSWarning1 >= 100)
{
newMeter.SMSWarning1Amount = sMSWarning1.Value;
}
if (billingDate != null)
{
newMeter.BillingDate = billingDate.ToIndiaDateTime();
}
_meterRepository.AddOrUpdate(newMeter);
var meterNotes = Helpers.MeterHelpers.Functions.GetMeterNote(oldMeter, newMeter);
Helpers.MeterHelpers.Functions.AddMeterNotes(meterNo, meterNotes);
totalProcessedMeters++;
}
}
TempData["SuccessMessage"] = totalProcessedMeters + " Meter(s) have been updated successfully";
}

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