I want to validate all Approve Item on Button click not N/A or Reject.Please suggest me how can I achive this task. Pls see the image.
int sum = 0;
foreach (DataListItem item in dtLstRejection.Items)
{
RadioButtonList rdlReasoncodeType ((RadioButtonList)item.FindControl("rdlReasonType"));
System.Web.UI.WebControls.Label lbldlmsg = (Label)item.FindControl("lbldlmsg");
{
if (rdlReasoncodeType.SelectedIndex == 0|| rdlReasoncodeType1.SelectedIndex== -1)
{
if (rdlReasoncodeType1.SelectedItem == null)
{
if (sum == 0)
{
lbldlmsg.Text = "*Approve fields are mandatory to check";
return; }}}}
else
{
sum++;
lbldlmsg.Text = "";
}
lbldlmsg.Text = "";
}}
Related
The following source code is intended to set focus to the immediately previous row of a deleted row.
Suppose I want to delete an unwanted word dddddddd from the database. When I press the Delete button, I want the word cynosure to be focused and placed at the top of the DataGridView which is not the case right now.
Right now, it is displayed at the bottom.
Source Code
void SetFocusToWord(Word concernedWord)
{
if (concernedWord != null)
{
int index = 0;
foreach (DataGridViewRow r in dataGridView1.Rows)
{
Word item = r.Tag as Word;
if (concernedWord.Name == item.Name)
{
dataGridView1.Focus();
dataGridView1.CurrentCell = dataGridView1.Rows[index].Cells[0];
break;
}
index++;
}
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
if (dataGridView1.SelectedRows.Count > 0)
{
int selectionIndex = dataGridView1.SelectedRows[0].Index;
foreach (DataGridViewRow r in dataGridView1.SelectedRows)
{
Word c = r.Tag as Word;
if (c != null)
{
_wordDatabase.Delete(c);
}
}
LoadToDataGridView();
if(selectionIndex > 0)
{
selectionIndex = selectionIndex - 1;
}
Word item = dataGridView1.Rows[selectionIndex].Tag as Word;
SetFocusToWord(item);
}
else
{
throw new Exception(SelectionErrorMessages.GetErrorMessageFor(typeof(Word)));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void LoadToDataGridView()
{
dataGridView1.Rows.Clear();
List<Word> items = (List<Word>)_wordDatabase.Get();
if (items != null)
{
if (items.Count > 0)
{
int i = 0;
foreach (Word c in items)
{
dataGridView1.Rows.Add(c.Name, c.Hint);
dataGridView1.Rows[i].Tag = c;
++i;
}
}
}
}
Reloading the database seems like an unnecessary step.
Based on how you want the grid to behave, try using code like this:
if (dataGridView1.SelectedRows.Count > 0) {
int selectIndex = dataGridView1.SelectedRows[0].Index;
dataGridView1.Rows.RemoveAt(selectIndex);
if (selectIndex > 0) {
dataGridView1.ClearSelection();
dataGridView1.Rows[selectIndex - 1].Selected = true;
dataGridView1.FirstDisplayedScrollingRowIndex = selectIndex - 1;
}
}
Poor performance and abundance of unnecessary code in your project are the result of you not using winforms binding properly. I suggest you start utilizing control's BindingContext and BindingSource accordingly. This should solve most of your problems.
For further details on winforms binding I recommend this docs.
Hello folks I am trying to update the quantity of a product that is being ordered. If the product already exists in the users 'basket' instead of inserting a new row, the quantity in the row with the existing item should be updated. It is updating but a new row is also inserted with the quantity that should have been added to the original row, like so:
I'm guessing something is wrong logically in my code but, I can't spot it.
private void btn_add_Click(object sender, EventArgs e)
{
try
{
ListViewItem item = new ListViewItem(list_Select_Product.SelectedItems[0].Text);
item.SubItems.Add(list_Select_Product.SelectedItems[0].SubItems[1].Text);
item.SubItems.Add(txt_quantity.Text);
bool ok = true;
if (!validNumbers(txt_quantity))
ok = false;
if (!validLength(txt_quantity, 1, 2))
ok = false;
if (ok == true)
{
foreach (ListViewItem lvi in list_view_orderitems.Items)
{
if(lvi.SubItems[0].Text == list_Select_Product.SelectedItems[0].Text)
{
int UpdateQunat = Convert.ToInt32(lvi.SubItems[2].Text);
int AddMe = Convert.ToInt32(txt_quantity.Text);
UpdateQunat = UpdateQunat + AddMe;
lvi.SubItems[2].Text = Convert.ToString(UpdateQunat);
list_view_orderitems.Items.Add(item);
}
else if (lvi.SubItems[0].Text != list_Select_Product.SelectedItems[0].Text)
{
list_view_orderitems.Items.Add(item);
}
}
if(list_view_orderitems.Items.Count == 0)
{
list_view_orderitems.Items.Add(item);
}
}
}
catch
{
MessageBox.Show("A product must be selected");
}
}
Look a little closer in the foreach loop. You actually add it there as well. (So you should remove that)
foreach (ListViewItem lvi in list_view_orderitems.Items)
{
if(lvi.SubItems[0].Text == list_Select_Product.SelectedItems[0].Text)
{
int UpdateQunat = Convert.ToInt32(lvi.SubItems[2].Text);
int AddMe = Convert.ToInt32(txt_quantity.Text);
UpdateQunat = UpdateQunat + AddMe;
lvi.SubItems[2].Text = Convert.ToString(UpdateQunat);
// adding it again. This line is not needed.
list_view_orderitems.Items.Add(item);
}
else if (lvi.SubItems[0].Text != list_Select_Product.SelectedItems[0].Text)
{
list_view_orderitems.Items.Add(item);
}
}
I this that it this if you need to get rid of the item.Add (i marked it:
if(lvi.SubItems[0].Text == list_Select_Product.SelectedItems[0].Text)
{
int UpdateQunat = Convert.ToInt32(lvi.SubItems[2].Text);
int AddMe = Convert.ToInt32(txt_quantity.Text);
UpdateQunat = UpdateQunat + AddMe;
lvi.SubItems[2].Text = Convert.ToString(UpdateQunat);
// list_view_orderitems.Items.Add(item);
}
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
My gridview missing previous data when post back. Here is the scenario, when I detect insufficient stock from gvFinalised gridview, I get the category, then I get the product with highest stock and display in gvSuggested gridview.
But let's say in my gvFinalised, there are three product with three different categories is insufficient, let's say they are Noodles, Canned Food and Beverages. It was supposed to display three different products with highest stock each from different categories in gvSuggested.
However, my problem now is, it just display the last items. For example, in this scenario, Beverages. The data before Beverages just get wiped out.
Here is the code on how I detect insufficient stock:
protected void tbQuantity_TextChanged(object sender, EventArgs e)
{
tempList = new Dictionary<string, string>();
distSPUItemList = new Dictionary<string, int>();
bool valid = true;
string quantityStr = "", prodID = "";
int packagesNeeded = 0, totalUnit = 0, quantity = 0;
//Get the total packages needed for this distribution
packagesNeeded = prodPackBLL.getPackagesNeededByDistributionID(distributionID);
foreach (GridViewRow gr in gvFinalised.Rows)
{
//Clear label error message
Label lblCheckAmount = gr.FindControl("lblCheckAmount") as Label;
lblCheckAmount.Text = "";
//Get the product variant ID which set as DataKeyNames and product quantity from selected row index
prodID = gvFinalised.DataKeys[gr.RowIndex].Value.ToString();
var tbQuantity = gr.FindControl("tbQuantity") as TextBox;
if (tbQuantity != null)
{
//Check if the input is numeric
quantityStr = tbQuantity.Text;
if (!int.TryParse(quantityStr, out quantity))
{
lblCheckAmount.Text = "Non-numeric input!";
TextBox tb = (TextBox)gr.FindControl("tbQuantity") as TextBox;
}
else
{
//Add both objects into Dictionary
tempList.Add(prodID, quantityStr);
}
}
}
//Portion to check the storage level for each products stored in tempList
//Loop thru tempList. key as prod variant ID, tempList.Keys as quantity
foreach (string key in tempList.Keys)
{
//Get total unit of each products
totalUnit = prodPackBLL.getTotalProductUnit(key);
valid = true;
//Check if unitQuantity exceed storage level
if (((Convert.ToInt32(tempList[key])) * packagesNeeded) > totalUnit)
{
//Get the label control in gridview
foreach (GridViewRow gr in gvFinalised.Rows)
{
if (key == gvFinalised.DataKeys[gr.RowIndex].Value.ToString())
{
//Change the color of textBox and display the insufficient message
valid = false;
//Automatically uncheck the checkBox if invalid
TextBox tb = (TextBox)gr.FindControl("tbQuantity") as TextBox;
Label lblCheckAmount = gr.FindControl("lblCheckAmount") as Label;
lblCheckAmount.Text = "Insufficient stock!";
//Here is the place where I collect the data and display in gvSuggested
getSuggested(key);
}
}
}
else
{
if (totalUnit - ((Convert.ToInt32(tempList[key])) * packagesNeeded) == 0)
{
foreach (GridViewRow gr in gvFinalised.Rows)
{
if (key == gvFinalised.DataKeys[gr.RowIndex].Value.ToString())
{
valid = true;
Label lblCheckAmount = gr.FindControl("lblCheckAmount") as Label;
lblCheckAmount.Attributes["style"] = "color:#ffb848";
lblCheckAmount.Text = "Stock becomes 0!";
}
}
}
}
//Portion to check for valid products to be inserted into distSPUItemList
if (valid)
{
//Set the textBox color
foreach (GridViewRow gr in gvFinalised.Rows)
{
if (key == gvFinalised.DataKeys[gr.RowIndex].Value.ToString())
{
TextBox tb = (TextBox)gr.FindControl("tbQuantity") as TextBox;
}
}
//Validated items store into another list to perform Sql statement when button on click
distSPUItemList.Add(key, (Convert.ToInt32(tempList[key]) * packagesNeeded));
}
}
}
And here is the getSuggested() method to populate my gvSuggeted:
protected void getSuggested(string prodVariantID)
{
string categoryName = prodPackBLL.getCategoryByProdVariantID(prodVariantID);
//Get the list of substitute product with highest storage level sorted in descending order
List<ProductPacking> prodSubstitute = new List<ProductPacking>();
List<string> lstCategory = new List<string>();
List<string> prodIDList = new List<string>();
List<DistributionStandardPackingUnitItems> distSPUItem = new List<DistributionStandardPackingUnitItems>();
distSPUItem = this.SuggestedItems;
//Find list of substitute with highest stock level and replace the product
prodSubstitute = prodPackBLL.getProductIDWithHighestStock(categoryName);
for (int count = 0; count < prodSubstitute.Count; count++)
{
//To prevent duplication of same product and select those catories which are in current category and counting them and taking them if there are less than 1 occurrences
if (!prodIDList.Contains(prodSubstitute[count].id) && !(lstCategory.Where(x => x.Equals(categoryName)).Select(x => x).Count() >= 2))
{
prodIDList.Add(prodSubstitute[count].id);
lstCategory.Add(categoryName);
}
}
for (int j = 0; j < prodIDList.Count; j++)
{
//Get the detail of the product added into prodList and add it into distSPUItem List
distSPUItem.Add(packBLL.getSPUItemDetailByID(prodIDList[j]));
}
gvSuggested.DataSource = distSPUItem;
gvSuggested.DataBind();
this.SuggestedItems = distSPUItem;
}
private List<DistributionStandardPackingUnitItems> SuggestedItems
{
get
{
if (ViewState["SuggestedItems"] == null)
{
return new List<DistributionStandardPackingUnitItems>();
}
else
{
return (List<DistributionStandardPackingUnitItems>)ViewState["SuggestedItems"];
}
}
set
{
ViewState["SuggestedItems"] = value;
}
}
I used a viewState to store the data when postback. However, it does not work. This line in gvSuggested:
this.SuggestedItems = distSPUItem;
causing my textbox in gridView not auto post back. If I removed it, the error above appear again. Any guides? Thanks in advance.
Please enable tbQuantity text box EnableAutoPostBack = True
I have these checkboxlist each cell of a gridview. Now, I am trying to get the selected items each checkboxlist but it failed. Any help please! Thanks!
foreach (GridViewRow gvRow in gvReg.Rows)
{
for (int ctr = 0; ctr <= 4 - 1; ctr++)
{
if (ctr == 0)
{
szCheckBoxListName = "cblMultiSelect";
szRegionName = "lblRegionName";
}
else
{
szCheckBoxListName = "cblMultiSelect" + ctr;
szRegionName = "lblRegionName" + ctr;
}
cbl=(CheckBoxList)gvRow.Cells[ctr].FindControl(szCheckBoxListName);
if (cbl.Items.Count > 0)
{
foreach (ListItem li in cbl.Items)
{
if (li.Selected)
{
iItemCount = iItemCount + 1;
}
}
}
}
}
itemCount returns zero always even if I have selected several items on those checkboxlists.
Are you data binding on Page_Load method? If yes, you must do this:
if(!IsPostBack)
{
GridView1.DataSource = Your Datas;
}