OnSelectedIndexChanged of asp.net DropDownList which is outside datalist - c#

I have a DataList that contains CheckBoxList, and I filter the datalist on selectedindexchanged outside datalist. The problem is when I select value from dropdownlist I can't get the checked values from database
and checkboxlist items count is 0
this is the code
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string GroupValue;
if (DropDownList1.SelectedValue.ToString().IsEmpty()) { GroupValue = null; } else { GroupValue = DropDownList1.SelectedValue.ToString(); }
if (pageMode == PageMode.Update)
{
int rowID = int.Parse(GrdUsers.GetRowValues(GrdUsers.FocusedRowIndex, "ID").ToString());
//ConnectionLayer cn = new ConnectionLayer();
//DataTable dt = cn.ExecutQuery("PagesSys", new object[] { 0, DropDownList1.SelectedItem.Text.ToString() });
//dlstPages.DataSource = dt;
//dlstPages.DataBind();
BindOption(rowID);
}
private void BindOption(int UserID)
{
try
{
if (pageMode == PageMode.Update)
{
if (DropDownList1.SelectedItem.Value != "-1")
{
dlstPages.DataSource = ViewState["FunctionOption"];
dlstPages.DataBind();
if (dlstPages.Items.Count > 0)
{
for (int i = 0; i < dlstPages.Items.Count; i++)
{
DataTable dt = new Users().UserPrivilege(UserID, int.Parse(dlstPages.DataKeys[i].ToString()));
if (dt.Rows.Count > 0)
{
dt.PrimaryKey = new DataColumn[] { dt.Columns["OptionId"] };
CheckBoxList chklist = (CheckBoxList)dlstPages.Items[i].FindControl("chkOption");
for (int j = 0; j < chklist.Items.Count; j++)
{
if (dt.Rows.Find(chklist.Items[j].Value) != null)
{
chklist.Items[j].Selected = true;
}
}
}
}
}
}
}
}
catch (Exception ex)
{
}
}

You need to use the arguments to the function to get the dropdown list object, then you can find the selected value. Something like:
DropDownList ddl= (DropDownList)sender;
var value = ddl.SelectedValue.ToString();

Related

ASP.NET - Retrieving Grid View Data when EnableViewState is Set to False

I am building an application that needs to display data in a GridView control, grouped by a particular value, and then export it to PDF.I used this set of classes here (http://www.agrinei.com/gridviewhelper/gridviewhelper_pt.htm) for grouping, and it works well. However, I had to set EnableViewState to false for it to work properly. The problem comes when I need to export it to PDF. Previously (before using GridViewHelper), this was working. However, it now generates an empty report (I suppose because EnableViewState is false).
How can I save the data and structure of the GridView produced through use of the GridViewHelper class in order to export it to PDF?
Some of my aspx (portions of code omitted for brevity)
public partial class all : System.Web.UI.Page
{
Int32 userID;
Int32 currentID;
protected void Page_Load(object sender, EventArgs e)
{
GridViewHelper helper = new GridViewHelper(allTicketGrid);
helper.RegisterGroup("propName", true, true);
helper.ApplyGroupSort();
userID = Convert.ToInt32(Session["userID"]);
if (Session["userLevel"] == null || Session["userLevel"] == "")
{
Response.Redirect("~/Default.aspx");
}
if (!IsPostBack)
{
this.populate();
}
}
protected void populate()
{
toDateBox.Text = DateTime.Now.ToShortDateString();
fromDateBox.Text = DateTime.Now.ToShortDateString();
using (ticketModel dbContext = new ticketModel())
{
END_USER user = dbContext.END_USER.First(u => u.END_USER_ID == userID);
itemCheckBoxList.DataSource = dbContext.ITEM_TYPE.ToList();
itemCheckBoxList.DataTextField = "DESCRIPTION";
itemCheckBoxList.DataValueField = "ITEM_TYPE_ID";
itemCheckBoxList.DataBind();
List<Int32> propIDList = new List<Int32>();
foreach(END_USER_PROPERTY item in user.END_USER_PROPERTY.ToList() ) {
propIDList.Add((Int32)item.PROPERTY_ID);
}
locationCheckBoxList.DataSource = dbContext.PROPERTies.Where(p=> propIDList.Contains(p.PROPERTY_ID)).ToList();
locationCheckBoxList.DataTextField = "SHORT_NAME";
locationCheckBoxList.DataValueField = "PROPERTY_ID";
locationCheckBoxList.DataBind();
}
}
protected void exportReport(object sender, EventArgs e)
{
DataTable dt = new DataTable();
for (int i = 0; i < allTicketGrid.Columns.Count; i++)
{
dt.Columns.Add(allTicketGrid.Columns[i].HeaderText);
}
foreach (GridViewRow rowView in allTicketGrid.Rows)
{
DataRow dr = dt.NewRow();
for (int i = 0; i < rowView.Cells.Count; i++)
{
dr[i] = rowView.Cells[i].Text.Trim();
}
dt.Rows.Add(dr);
}
Document doc = pdfWorker.readyDocument();
pdfWorker.createTable(doc, dt);
String filePath = Server.MapPath("~/reports/files/");
String fileName = "report_" + DateTime.Now.ToString("MM-dd-yyyy") + ".pdf";
filePath += fileName;
pdfWorker.savePDF(doc, filePath);
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.TransmitFile(filePath);
Response.End();
}
protected void generateReport(object sender, EventArgs e)
{
int[] selectedLocations = getLocations();
int[] selectedItemTypes = getItems();
DateTime from = Convert.ToDateTime(fromDateBox.Text);
DateTime to = Convert.ToDateTime(toDateBox.Text);
if (!allButton.Checked)
{
Int32 statusID;
if (openButton.Checked)
{
statusID = 1;
}
else
{
statusID = 2;
}
using (ticketModel dbContext = new ticketModel())
{
allTicketGrid.DataSource = dbContext.TICKETs.Where(t => t.STATUS_TYPE.STATUS_TYPE_ID == statusID && selectedLocations.Contains(t.PROPERTY_ID) && selectedItemTypes.Contains(t.ITEM_TYPE_ID) && t.OPEN_STATUS.UPDATED_DATE >= from && t.OPEN_STATUS.UPDATED_DATE <= to).ToList();
allTicketGrid.DataBind();
}
}
else
{
using (ticketModel dbContext = new ticketModel())
{
allTicketGrid.DataSource = dbContext.TICKETs.Where(t => selectedLocations.Contains(t.PROPERTY_ID) && selectedItemTypes.Contains(t.ITEM_TYPE_ID) && t.OPEN_STATUS.UPDATED_DATE >= from && t.OPEN_STATUS.UPDATED_DATE <= to).ToList();
allTicketGrid.DataBind();
}
}
}
and my pdfWorker class:
static class pdfWorker
{
public static Document readyDocument() {
Document doc = new Document();
Section section = doc.AddSection();
Style docStyles = doc.Styles["Normal"];
docStyles.Document.DefaultPageSetup.Orientation = MigraDoc.DocumentObjectModel.Orientation.Landscape;
docStyles.Font.Size = 8;
docStyles.ParagraphFormat.FirstLineIndent = 0;
return doc;
}
public static void createTable(Document document, DataTable dataTable)
{
Table table = new Table();
table.Format.Font.Size = 6;
table.BottomPadding = 10;
int colCount = dataTable.Columns.Count;
Row pdfRow;
Cell pdfCell;
for (int i = 0; i < colCount; i++)
{
table.AddColumn();
}
pdfRow = table.AddRow();
for (int i = 0; i < colCount; i++)
{
pdfCell = pdfRow.Cells[i];
pdfCell.Row.Format.Font.Size = 10;
pdfCell.AddParagraph(dataTable.Columns[i].ToString());
}
foreach (DataRow row in dataTable.Rows)
{
pdfRow = table.AddRow();
pdfRow.HeightRule = RowHeightRule.AtLeast;
for (int i = 0; i < colCount; i++)
{
pdfCell = pdfRow.Cells[i];
pdfCell.AddParagraph(row[i].ToString());
}
}
document.LastSection.Add(table);
}
public static void savePDF(Document doc, String fileName) {
PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always);
SaveFileDialog saveDialog = new SaveFileDialog();
renderer.Document = doc;
renderer.RenderDocument();
renderer.PdfDocument.Save(fileName);
}
}
}
Thanks so much for any help.
You can put the code that populates the GridView in a separate method:
protected void generateReport(object sender, EventArgs e)
{
BindReportData();
}
private void BindReportData()
{
int[] selectedLocations = getLocations();
int[] selectedItemTypes = getItems();
DateTime from = Convert.ToDateTime(fromDateBox.Text);
DateTime to = Convert.ToDateTime(toDateBox.Text);
if (!allButton.Checked)
{
Int32 statusID;
if (openButton.Checked)
{
statusID = 1;
}
else
{
statusID = 2;
}
using (ticketModel dbContext = new ticketModel())
{
allTicketGrid.DataSource = dbContext.TICKETs.Where(t => t.STATUS_TYPE.STATUS_TYPE_ID == statusID && selectedLocations.Contains(t.PROPERTY_ID) && selectedItemTypes.Contains(t.ITEM_TYPE_ID) && t.OPEN_STATUS.UPDATED_DATE >= from && t.OPEN_STATUS.UPDATED_DATE <= to).ToList();
allTicketGrid.DataBind();
}
}
else
{
using (ticketModel dbContext = new ticketModel())
{
allTicketGrid.DataSource = dbContext.TICKETs.Where(t => selectedLocations.Contains(t.PROPERTY_ID) && selectedItemTypes.Contains(t.ITEM_TYPE_ID) && t.OPEN_STATUS.UPDATED_DATE >= from && t.OPEN_STATUS.UPDATED_DATE <= to).ToList();
allTicketGrid.DataBind();
}
}
}
And call that method at the start of exportReport:
protected void exportReport(object sender, EventArgs e)
{
BindReportData();
...
}

How to read from a GridView

Solution, for at least a specific cell: GridView1.Rows[i].Cells[j].Text;
I've build a simple CSV-Fileupload. After the user uploaded the file he should be able to evaluate the data. When the fileupload was successful the data gets loaded into the GridView1, with this code: (Problem below the code)
string[] readCSV = File.ReadAllLines(lblFilePath.Text);
DataTable dt = new DataTable();
bool bSplitMe = false;
foreach (var rLine in readCSV)
{
if (bSplitMe)
{
string[] aSplittedLine = rLine.Split(";".ToCharArray());
try
{
dt.Rows.Add(aSplittedLine);
}
catch(System.Exception)
{
txtBoxFileOut.Text = rLine;
break;
}
}
else
{
if (rLine.ToLower().StartsWith("definedtestid;"))
{
bSplitMe = true;
string[] aSplittedLine = rLine.Split(";".ToCharArray());
foreach (var rCol in aSplittedLine)
{
dt.Columns.Add(rCol);
}
}
else
{
txtBoxFileOut.Text += rLine.ToString() + "\n";
}
}
}
dt.Columns.Remove("Column1");
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
if (string.IsNullOrEmpty(dt.Rows[i][j].ToString()))
{
dt.Rows[i][j] = "0";
}
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
After this the user should be able to select a row and display the data from that row in a chart.
Problem: I'm not able to read data from the cells I want, or to read from a "hardcoded" cell.
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) {
GridViewRow row = GridView1.SelectedRow;
txtOutputfield.Text = row.Cells[2].Text;
}
Please check your cell index. Is it correct? For example: the third column will have index "2" not "3"
And, if you use a control to store the data, you need to find that control:
txtOutputfield.Text =
row.Cells[2].FindControl('placeyourcontrolnamehere').Text;
For a specific Cell this worked fine
txtOutputfield.Text = GridView1.Rows[i].Cells[j].Text;

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

GridView missing data between postbacks

So basically I am doing a manage packaging item system. The scenario is, when I select from gvSPU, gvFinalised should display the item in database. After that, when I add new item into the gvFinalised, it supposed to keep stacking up the items instead of wiping out the previous record and display the added latest one. Here is the code:
private List<DistributionStandardPackingUnitItems> tempDistSPUI
{
get
{
if (ViewState["tempDistSPUI"] == null)
{
return new List<DistributionStandardPackingUnitItems>();
}
else
{
return (List<DistributionStandardPackingUnitItems>)ViewState["tempDistSPUI"];
}
}
set
{
ViewState["tempDistSPUI"] = value;
}
}
protected void gvSPU_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
int packagesNeeded = prodPackBLL.getPackagesNeededByDistributionID(distributionID);
int rowNo = int.Parse(e.CommandArgument.ToString());
SPUname = this.gvSPU.DataKeys[rowNo].Value.ToString();
lblSPUname.Text = SPUname;
List<DistributionStandardPackingUnitItems> templist = new List<DistributionStandardPackingUnitItems>();
templist = tempDistSPUI;
templist = packBLL.getAllDistSPUItemByDistributionIDnSPUName(distributionID, SPUname);
gvFinalised.DataSource = templist;
gvFinalised.DataBind();
this.tempDistSPUI = templist;
}
When gvSPU row is selected, it should store all the records into templist and display in gvFinalised.
List<string> prodVariantIDList = new List<string>();
private List<string> SelectedVariantDetailIDs
{
get
{
if (ViewState["SelectedVariantDetailIDs"] == null)
{
return new List<string>();
}
else
{
return (List<string>)ViewState["SelectedVariantDetailIDs"];
}
}
set
{
ViewState["SelectedVariantDetailIDs"] = value;
}
}
protected void lbnAdd_Click(object sender, EventArgs e)
{
List<ProductPacking> prodVariantDetail = new List<ProductPacking>();
int packagesNeeded = prodPackBLL.getPackagesNeededByDistributionID(distributionID);
// get the last product variant IDs from ViewState
prodVariantIDList = this.SelectedVariantDetailIDs;
foreach (RepeaterItem ri in Repeater1.Items)
{
GridView gvProduct = (GridView)ri.FindControl("gvProduct");
foreach (GridViewRow gr in gvProduct.Rows)
{
CheckBox cb = (CheckBox)gr.FindControl("cbCheckRow");
//Prevent gvFinalised to store duplicate products
if (cb.Checked && !prodVariantIDList.Any(i => i == gvProduct.DataKeys[gr.RowIndex].Value.ToString()))
{
// add the corresponding DataKey to idList
prodVariantIDList.Add(gvProduct.DataKeys[gr.RowIndex].Value.ToString());
}
}
}
for (int i = 0; i < prodVariantIDList.Count; i++)
{
prodVariantDetail.Add(prodPackBLL.getProdVariantDetailByID(prodVariantIDList[i]));
}
gvFinalised.DataSource = prodVariantDetail;
gvFinalised.DataBind();
// save prodVariantIDList to ViewState
this.SelectedVariantDetailIDs = prodVariantIDList;
}
When add button is on click, it should append with the record in gridview instead of wiping them off and insert the checked one.
I am using the viewState to store the record between postbacks. However, when I try to add new item into gvFinalised, the previous record which in the templist will disappear and the gvFinalised will be populated with the result from prodVariantDetail list.
Any guide? Thanks in advance.
EDIT
List<DistributionStandardPackingUnitItems> itemList = new List<DistributionStandardPackingUnitItems>();
protected void gvSPU_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
int packagesNeeded = prodPackBLL.getPackagesNeededByDistributionID(distributionID);
int rowNo = int.Parse(e.CommandArgument.ToString());
SPUname = this.gvSPU.DataKeys[rowNo].Value.ToString();
lblSPUname.Text = SPUname;
itemList = tempDistSPUI;
itemList = packBLL.getAllDistSPUItemByDistributionIDnSPUName(distributionID, SPUname);
gvFinalised.DataSource = itemList;
gvFinalised.DataBind();
this.tempDistSPUI = itemList;
}
protected void lbnAdd_Click(object sender, EventArgs e)
{
List<DistributionStandardPackingUnitItems> prodVariantDetail = new List<DistributionStandardPackingUnitItems>();
int packagesNeeded = prodPackBLL.getPackagesNeededByDistributionID(distributionID);
// get the last product variant IDs from ViewState
prodVariantIDList = this.SelectedVariantDetailIDs;
foreach (RepeaterItem ri in Repeater1.Items)
{
GridView gvProduct = (GridView)ri.FindControl("gvProduct");
foreach (GridViewRow gr in gvProduct.Rows)
{
CheckBox cb = (CheckBox)gr.FindControl("cbCheckRow");
//Prevent gvFinalised to store duplicate products
if (cb.Checked && !prodVariantIDList.Any(i => i == gvProduct.DataKeys[gr.RowIndex].Value.ToString()))
{
// add the corresponding DataKey to idList
prodVariantIDList.Add(gvProduct.DataKeys[gr.RowIndex].Value.ToString());
}
}
}
for (int i = 0; i < prodVariantIDList.Count; i++)
{
prodVariantDetail.Add(packBLL.getProdVariantDetailByID(prodVariantIDList[i]));
}
for (int j = 0; j < itemList.Count; j++)
{
prodVariantDetail.Add(itemList[j]);
}
gvFinalised.DataSource = prodVariantDetail;
gvFinalised.DataBind();
}
// save prodVariantIDList to ViewState
this.SelectedVariantDetailIDs = prodVariantIDList;
}
You have to add the elements of tempDistSPUI into prodVariantDetail before binding prodVariantDetail to gvFinalised.
Here's what I would do using List.AddRange Method:
protected void lbnAdd_Click(object sender, EventArgs e)
{
List<DistributionStandardPackingUnitItems> prodVariantDetail = new List<DistributionStandardPackingUnitItems>();
int packagesNeeded = prodPackBLL.getPackagesNeededByDistributionID(distributionID);
// get the last product variant IDs from ViewState
prodVariantIDList = this.SelectedVariantDetailIDs;
foreach (RepeaterItem ri in Repeater1.Items)
{
GridView gvProduct = (GridView)ri.FindControl("gvProduct");
foreach (GridViewRow gr in gvProduct.Rows)
{
CheckBox cb = (CheckBox)gr.FindControl("cbCheckRow");
//Prevent gvFinalised to store duplicate products
if (cb.Checked && !prodVariantIDList.Any(i => i == gvProduct.DataKeys[gr.RowIndex].Value.ToString()))
{
// add the corresponding DataKey to idList
prodVariantIDList.Add(gvProduct.DataKeys[gr.RowIndex].Value.ToString());
}
}
}
for (int i = 0; i < prodVariantIDList.Count; i++)
{
prodVariantDetail.Add(packBLL.getProdVariantDetailByID(prodVariantIDList[i]));
}
// get the content of tempDistSPUI from ViewState
itemList = this.tempDistSPUI;
// add all elements of itemList to prodVariantDetail
prodVariantDetail.AddRange(itemList);
gvFinalised.DataSource = prodVariantDetail;
gvFinalised.DataBind();
// save prodVariantIDList to ViewState
this.SelectedVariantDetailIDs = prodVariantIDList;
}

How to delete multiple checked items in a ListView?

protected void btndelete_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
for (int i = 0; i < listview1.Items.Count; i++)
{
ListViewDataItem items = listview1.Items[i];
CheckBox chkBox = (CheckBox)items.FindControl("chkdel");
if (chkBox.Checked == true)
{
if (Session["CurrentTable"] != null)
{
dt = (DataTable)Session["CurrentTable"];
dt.Rows.RemoveAt(i);
}
}
else
{
}
}
Session["CurrentTable"] = dt;
listview1.DataSource = dt;
listview1.DataBind();
BindDataToGridviewDropdownlist();
}
Here it is deleting one row only. How to delete multiple checked items in listview?
As mentioned by Hans Derks above in comment, you are taking data table from session each time but not actually updating it using Session["CurrentTable"]=dt; like:
protected void btndelete_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
for (int i = 0; i < listview1.Items.Count; i++)
{
ListViewDataItem items = listview1.Items[i];
CheckBox chkBox = (CheckBox)items.FindControl("chkdel");
if (chkBox.Checked == true)
{
if (Session["CurrentTable"] != null)
{
dt = (DataTable)Session["CurrentTable"];
dt.Rows.RemoveAt(i);
Session["CurrentTable"]=dt;
listview1.DataSource = dt;
listview1.DataBind();
}
}
else
{
}
}
BindDataToGridviewDropdownlist();
}
Refactored version of Pranav's answer:
protected void btndelete_Click(object sender, EventArgs e)
{
// Get the Table from the session.
DataTable dt = (DataTable)Session["CurrentTable"];
// Only actually proceed, if we have a value.
if(dt != null)
{
// Loop through each item.
for (int i = 0; i < listview1.Items.Count - 1; i++)
{
// Find the checkbox to determine if it's checked.
ListViewDataItem items = listview1.Items[i];
CheckBox chkBox = (CheckBox)items.FindControl("chkdel");
if (chkBox.Checked == true)
{
// Remove the row at the current index.
dt.rows.RemoveAt(i);
}
}
// Update the session and rebind the data.
Session["CurrentTable"] = dt;
listview1.DataSource = dt;
listview1.DataBind();
BindDataToGridviewDropdownlist();
}
}
This works for me .....
protected void btndelete_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
if (Session["CurrentTable"] != null)
{
dt = (DataTable)Session["CurrentTable"];
int j = 0;
for (int i = 0; i < listview1.Items.Count; i++)
{
ListViewDataItem items = listview1.Items[i];
CheckBox chkBox = (CheckBox)items.FindControl("chkdel");
if (chkBox.Checked == true)
{
dt.Rows.RemoveAt(j);
dt.AcceptChanges();
}
else
{
j++;
}
}
Session["CurrentTable"] = dt;
listview1.DataSource = dt;
listview1.DataBind();
BindDataToGridviewDropdownlist();
}
}

Categories