I am using below query
DataRow[] oFilteredRows =
oTrgFTPTrigList.Select($"ftpPath='{oSrcRow["ftpPath"]}'
and ftpUserName='{oSrcRow["ftpUserName"]}'");
But it fails since ftpPath is url ftp://testURL/
I need to filter and get records with same data as of source (Comparing target and source DataBases)
Here is the answer.
I have converted data like below.
string ftpPath = Uri.EscapeUriString(oSrcRow["ftpPath"].ToString());
Here is the full code sample.
public DataTable compareFTPTriggers(string targetConnectionString)
{
DataTable oFTPTriggerTableDiffs = new DataTable("oFTPTriggerDiffs");
oFTPTriggerTableDiffs.Columns.Add("oFTPTriggerID");
oFTPTriggerTableDiffs.Columns.Add("oFTPTriggerName");
oFTPTriggerTableDiffs.Columns.Add("Comments");
try
{
deFTPTrigger oSrcFTPTrigger = new deFTPTrigger(m_connectString, m_externalUserID);
DataTable oSrcFTPTrigList = oSrcFTPTrigger.getAllFTPTriggers();
string systemUserID = clsSettings.systemUserID(targetConnectionString);
deFTPTrigger oTrgFTPTrigger = new deFTPTrigger(targetConnectionString, systemUserID);
DataTable oTrgFTPTrigList = oTrgFTPTrigger.getAllFTPTriggers();
foreach (DataRow oSrcRow in oSrcFTPTrigList.Rows)
{
string ftpPath = Uri.EscapeUriString(oSrcRow["ftpPath"].ToString());
DataRow[] oFilteredRows = oTrgFTPTrigList.Select($"ftpPath= '{ftpPath}' and ftpUserName='{oSrcRow["ftpUserName"]}'");
string sKey = $"{oSrcRow["ftpPath"]} - {oSrcRow["ftpUserName"]}";
if (oFilteredRows.Length == 0)
{
oFTPTriggerTableDiffs.Rows.Add(oSrcRow["ftpTriggerID"], sKey, "Addition");
}
else
{
if (
oSrcRow["ftpPassword"].ToString() != oFilteredRows[0]["ftpPassword"].ToString() ||
oSrcRow["waitTime"].ToString() != oFilteredRows[0]["waitTime"].ToString() || oSrcRow["waitType"].ToString() != oFilteredRows[0]["waitType"].ToString() ||
oSrcRow["definitionID"].ToString() != oFilteredRows[0]["definitionID"].ToString() || oSrcRow["variableName"].ToString() != oFilteredRows[0]["variableName"].ToString() ||
oSrcRow["enabled"].ToString() != oFilteredRows[0]["enabled"].ToString() || oSrcRow["globalName"].ToString() != oFilteredRows[0]["globalName"].ToString()
)
{
oFTPTriggerTableDiffs.Rows.Add(oSrcRow["ftpTriggerID"], sKey, "Properties are different");
}
}
}
}
catch (Exception ex)
{
// m_oErrorProvider.writeError(ex.Message);
}
DataView dvSorted = oFTPTriggerTableDiffs.DefaultView;
dvSorted.Sort = "oFTPTriggerName ASC";
oFTPTriggerTableDiffs = dvSorted.ToTable();
return (oFTPTriggerTableDiffs);
}
I'm loading a DataTable from a Database and but do not want to have it the way it looks. That’s why I decided to create a new DataTable and fill it with my received Data.
Unfortunately, the data are not fully shown in the DataGrid. To be more detailed, only the first column is shown but all other are not. While debugging I could ensure that the DataTable is filled correctly.
Does anyone of you have an idea what I am doing wrong?
Model:
internal DataTable getValueTable(ObservableCollection<CheckableMenuitem> listSelectableValues)
{
DataTable TableToReturn = new DataTable();
string LaborValueColumnCaption = Properties.Resources.LabValueColumnCaption;
TableToReturn.Columns.Add(LaborValueColumnCaption);
List<string> selectedValueNames = new List<string>();
foreach (CheckableMenuitem item in listSelectableValues.Where(x => x.IsChecked == true))
{
selectedValueNames.Add(item.Caption);
}
string selectionFormular = "Wertname in ('" + string.Join("', '", selectedValueNames) + "')";
DataRow[] selectionRows = fullValueTable.Select(selectionFormular);
HashSet<DateTime> ListOfDays = new HashSet<DateTime>();
foreach (DataRow item in selectionRows)
{
DateTime? Tmp = Functions.ParseNullableDate(item["Messdatum"].ToString());
if (Tmp != null)
{
ListOfDays.Add(((DateTime)Tmp).Date);
}
}
string DateFormatString = "dd.MM.yyyy";
foreach (DateTime date in ListOfDays)
{
TableToReturn.Columns.Add(date.ToString(DateFormatString));
}
foreach (var valueName in selectedValueNames)
{
string singleSelectionFormular = "Wertname ='" + valueName + "'";
List<DataRow> singleSelectionRows = fullValueTable.Select(singleSelectionFormular).ToList();
if (singleSelectionRows.Count() == 1)
{
DateTime? ValueDate = Functions.ParseNullableDate(singleSelectionRows[0]["Messdatum"].ToString());
if (ValueDate != null)
{
}
DataRow newRow = TableToReturn.NewRow();
//erste Spalte
newRow[LaborValueColumnCaption] = valueName;
string spalte = ((DateTime)ValueDate).ToString(DateFormatString);
newRow[spalte] = singleSelectionRows[0]["MESSWERT_ALPHA"].ToString();
//newRow[((DateTime)ValueDate).ToString(DateFormatString)] = singleSelectionRows[0]["MESSWERT_ALPHA"].ToString();
TableToReturn.Rows.Add(newRow);
}
if (singleSelectionRows.Count() > 1)
{
List<DataRow> Rows = new List<DataRow>() { TableToReturn.NewRow() };
Rows[0][LaborValueColumnCaption] = valueName;
HashSet<DateTime> usedDates = new HashSet<DateTime>();
foreach (var item in singleSelectionRows)
{
DateTime? ValueDate = Functions.ParseNullableDate(singleSelectionRows[0]["Messdatum"].ToString());
if (ValueDate != null)
{
DateTime Date = ((DateTime)ValueDate).Date;
if (usedDates.Add(Date))
{
string name = "Wertname ='" + valueName + "' and Messdatum > " + Date + " and Messdatum < " + Date.AddDays(1);
DataRow[] test2 = fullValueTable.Select(singleSelectionFormular);
//Rows[0][((DateTime)ValueDate).ToString(DateFormatString)] = singleSelectionRows[0]["MESSWERT_ALPHA"].ToString();
}
}
}
foreach (DataRow newRow in Rows)
{
TableToReturn.Rows.Add(newRow);
}
}
}
return TableToReturn;
}
ViewModel:
public DataTable ValueTable
{
get
{
return model.getValueTable(ListSelectableValues);
}
}
View:
<DataGrid DockPanel.Dock="Top" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" AutoGenerateColumns="True" ItemsSource="{Binding Path=ValueTable}"/>
edit:
enter image description here
the problem lays on the date format:
wpf datatable column name can not have slash /
Cheers,
Marco
I am developing the my asp.net project, I'm try to make ASP.net text box for Auto Generate code, but its not working correctly, sample Auto Generate code = ID1.
I'm try to use this part,
string txt = txtBatchNo.Text;
txtBatchNo.Text = "C" + Convert.ToInt32(txt.Substring(1, txt.Length - 1)) + 1;
Code:
protected void btnAdd_Click(object sender, EventArgs e)
{
int newId = 1;
if (selectGRNDetailId == -1)
{
{
try
{
if (dtFabricItem.Rows.Count > 0)
{
newId = Convert.ToInt32(dtFabricItem.Rows[dtFabricItem.Rows.Count - 1]["GRNDetailsID"].ToString()) + 1;
}
}
catch (Exception)
{
newId = 1;
}
}
}
else
{
newId = selectGRNDetailId;
}
if (dtFabricItem == null)
{
CreateFabricDetails();
dtFabricItem = dt;
}
else
{
CreateFabricDetails();
}
DataRow dr2 = null;
dr2 = dt.NewRow();
dr2["GRNDetailsID"] = newId;
dr2["GRNDetailID"] = selectGRNId;
dr2["BatchNO"] = txtBatchNo.Text;
dr2["ItemId"] = Convert.ToInt32(ddlYarnName.SelectedValue);
dr2["ItemName"] = ddlYarnName.SelectedItem.Text;
dr2["LotId"] = Convert.ToInt32(ddlLotNo.SelectedValue);
dr2["LotName"] = ddlLotNo.SelectedItem.Text;
dr2["FibetLot"] = txtFiberLot.Text;
dr2["ContainsNo"] = txtContainsNO.Text;
dr2["Shade"] = txtShade.Text;
dr2["Quantity"] = Convert.ToDecimal(txtQty.Text).ToString();
dr2["YarnPrice"] = Convert.ToDecimal(txtYarnPrice.Text).ToString();
dr2["Cornweight"] = Convert.ToDecimal(txtCornWeight.Text).ToString();
dr2["BoxWeight"] = Convert.ToDecimal(txtBoxWeight.Text).ToString();
dr2["NumberofCones"] = Convert.ToDecimal(txtNumberofcones.Text).ToString();
dr2["Numberofboxes"] = Convert.ToDecimal(txtNumberofboxes.Text).ToString();
dt.Rows.Add(dr2);
//txtNumberofcones.Text = (Convert.ToDecimal(txtBoxWeight.Text) / Convert.ToDecimal(txtCornWeight.Text)).ToString();
if (dtFabricItem == null || dtFabricItem.Rows.Count == 0)
{
dtFabricItem = dt;
dtFabricItem.PrimaryKey = new DataColumn[] { dtFabricItem.Columns["GRNDetailsID"] };
}
else
{
dtFabricItem.PrimaryKey = new DataColumn[] { dtFabricItem.Columns["GRNDetailsID"] };
dtFabricItem.Merge(dt);
}
//dtFabricItem.PrimaryKey = new DataColumn[] { dtFabricItem.Columns["GRNDetailsID"] };
dtFabricItem.AcceptChanges();
gvrItemDetails.DataSource = dtFabricItem;
gvrItemDetails.DataBind();
selectGRNDetailId = -1;
ClearDetails();
}
TextBox Id = `txtBatchNo`
I have my problem in my datagrid view.
The datagridview is from the text file:
Student Name|Grade Level|Student Number|Gender
John,Grade 7,54015,1
Jessy,Grade 3,20147,2
Kyle,Grade 9,41812,1
Howard,Grade 6,8436,1
And my code:
var lines = File.ReadAllLines(#"C:\Users\1\Desktop\1.txt");
if (lines.Count() > 0)
{
foreach (var columnName in lines.FirstOrDefault()
.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries))
{
dataGridView1.Columns.Add(columnName, columnName);
}
foreach (var cellValues in lines.Skip(1))
{
var cellArray = cellValues
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
if (cellArray.Length == dataGridView1.Columns.Count)
dataGridView1.Rows.Add(cellArray);
}
foreach (var columnName in lines.First()
.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries))
{
if (columnName == "Gender")
{
var dgc = new DataGridViewComboBoxColumn() { Name = "hi", HeaderText = "bye" };
// dgc.Items.AddRange("Male", "Female");
DataTable dt = new DataTable();
DataColumn dc1 = new DataColumn("ID");
DataColumn dc2 = new DataColumn("Name");
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
dt.Rows.Add(1, "Male");
dt.Rows.Add(2, "Female");
DataGridViewComboBoxColumn c1 = new DataGridViewComboBoxColumn();
c1.DataSource = dt;
c1.DisplayMember = "Name";
c1.ValueMember = "ID";
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i]["ID"].ToString() == "1") // 1 for MALE & 2 for FEMALE
{
c1.DefaultCellStyle.NullValue = dt.Rows[i]["Name"];
}
}
dataGridView1.Columns.Add(c1);
continue;
}
}
}
What i want is to remove the 3rd column and replace it by the fourth column and also to change the value of this
if (dt.Rows[i]["ID"].ToString() == "1") // 1 for MALE & 2 for FEMALE
on value member ID
to the fourth value of a line in the text file.
John,Grade 7,54015,1
Jessy,Grade 3,20147,2
Kyle,Grade 9,41812,1
Howard,Grade 6,8436,1
If the value is 1, the default value of combobox is male.
While, if the value 2, the default value of combobox is female.
Can anyone fix and edit my code?
Thanks to everyone!
Try changing your first loop to handle the "gender" column differently than the rest.
Create a ComboBox column and populate it with the two gender values.
foreach (var columnName in lines.First()
.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries))
{
if (columnName == "Gender")
{
var dgc = new DataGridViewComboBoxColumn() { HeaderText = "Gender" };
dgc.Items.AddRange(
new KeyValuePair<string, string>("1", "Male"),
new KeyValuePair<string, string>("2", "Female"));
dgc.ValueMember = "Key";
dgc.DisplayMember = "Value";
dataGridView1.Columns.Add(dgc);
continue;
}
dataGridView1.Columns.Add(columnName, columnName);
}
Then when you add your rows of data, including the gender, it should display correctly in the ComboBox but also allow you to change the value.
Edit (update for setting a default value in the ComboBox):
foreach (var cellValues in lines.Skip(1))
{
var cellArray = cellValues.Split(new[] { ',' });
if (cellArray.Length == dataGridView1.Columns.Count)
{
if (String.IsNullOrEmpty(cellArray[dataGridView1.Columns.Count]))
cellArray[dataGridView1.Columns.Count] = "1";
dataGridView1.Rows.Add(cellArray);
}
}
Basically, the above just looks at the last "column" from the file and, if it's empty, then default to "Male".
I also removed StringSplitOptions.RemoveEmptyEntries. That option will only return 3 elements in cellArray when the gender column is empty, which will also cause cellArray.Length == dataGridView1.Columns.Count to fail.
This works,
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.Rows.Add(1, "Male");
dt.Rows.Add(2, "Female");
var lines = File.ReadAllLines(#"C:\Users\1\Desktop\1.txt");
if (lines.Count() > 0)
{
foreach (var columnName in lines.FirstOrDefault()
.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries))
{
if (columnName == "Gender")
{
var c1 = new DataGridViewComboBoxColumn();
c1.DataSource = dt;
c1.DisplayMember = "Name";
c1.ValueMember = "ID";
c1.HeaderText = "Gender";
dataGridView1.Columns.Add(c1);
continue;
}
dataGridView1.Columns.Add(columnName, columnName);
}
foreach (var cellValues in lines.Skip(1))
{
var cellArray = cellValues
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
if (cellArray.Length == dataGridView1.Columns.Count)
dataGridView1.Rows.Add(cellArray);
}
}
I also like to point out that you are using
cellValues.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
which could be dangerous, because of StringSplitOptions.RemoveEmptyEntries the entry
Hulk,,8436,1
would be skipped.
And I would suggest you use a DataTable as a DataSource
private void Form1_Shown(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.Rows.Add(1, "Male");
dt.Rows.Add(2, "Female");
var table = GetDataTable(#"C:\temp\1.txt");
foreach (DataColumn column in table.Columns)
{
var columnName = column.ColumnName;
DataGridViewColumn col;
if (columnName == "Gender")
{
var c1 = new DataGridViewComboBoxColumn();
c1.DataSource = dt;
c1.DisplayMember = "Name";
c1.ValueMember = "ID";
col = c1;
}
else
{
col = new DataGridViewTextBoxColumn();
}
col.HeaderText = "Gender";
col.DataPropertyName = columnName;
dataGridView1.Columns.Add(col);
}
dataGridView1.DataSource = table;
}
the method could look like this
private DataTable GetDataTable(string fileName)
{
var table = new DataTable();
var lines = File.ReadAllLines(#"C:\temp\1.txt");
if (lines.Count() > 0)
{
foreach (var columnName in lines.FirstOrDefault()
.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries))
{
table.Columns.Add(columnName);
}
foreach (var cellValues in lines.Skip(1))
{
var cellArray = cellValues
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
if (cellArray.Length == table.Columns.Count)
table.Rows.Add(cellArray);
}
}
return table;
}
Do something like this,
public partial class Form1 : Form
{
bool bIsComboBox = false;
delegate void SetComboBoxCellType(int iRowIndex);
DataTable dt = new DataTable();
public Form1()
{
InitializeComponent();
var lines = File.ReadAllLines(#"C:\\1.txt");
if (lines.Count() > 0)
{
foreach (var columnName in lines.FirstOrDefault()
.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries))
{
dt.Columns.Add(columnName, typeof(string));
}
foreach (var cellValues in lines.Skip(1))
{
var cellArray = cellValues
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
// if (cellArray.Length == dataGridView1.Columns.Count)
dt.Rows.Add(cellArray);
}
dataGridView1.DataSource = dt;
}
}
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
SetComboBoxCellType objChangeCellType = new SetComboBoxCellType(ChangeCellToComboBox);
if (e.ColumnIndex == this.dataGridView1.Columns["Gender"].Index)
{
this.dataGridView1.BeginInvoke(objChangeCellType, e.RowIndex);
bIsComboBox = false;
}
}
private void ChangeCellToComboBox(int iRowIndex)
{
if (bIsComboBox == false)
{
DataGridViewComboBoxCell dgComboCell = new DataGridViewComboBoxCell();
dgComboCell.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
dgComboCell.DataSource = dt;
dgComboCell.ValueMember = "Gender";
dgComboCell.DisplayMember = "Gender";
dataGridView1.Rows[iRowIndex].Cells[dataGridView1.CurrentCell.ColumnIndex] = dgComboCell;
bIsComboBox = true;
}
}
I am trying to get the items stored in a sessions variable into a repeater for users to see. However, I am not entirely sure how to do it (I'm new to session variables). Basically, when users enter in quantities for items on once page the hit submit, they are taken to an "order summary" page, which will display what they plan to purchase. I have successfully set up a session variable to contain the sku and quantity of each product the user selects, but I do not know how to get the information out.
I've stored the information in the session variable as [sku],[quantity];[sku],[quantity];[sku],[quantity] and so on. I figure I must do a split or something based on the commas and semicolons but I am not sure how to do so with a session variable.
The code for the product listing page that contains the information to be stored in the session variable:
public partial class GojoptproductlistSublayout : System.Web.UI.UserControl
{
private void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
Item CurrentItem = Sitecore.Context.Item;
Item HomeItem = ScHelper.FindAncestor(CurrentItem, "gojoMarket");
if (HomeItem != null)
{
Item ProductGroup = HomeItem.Axes.SelectSingleItem(#"child::*[##templatename='gojoMarketOfficeBuildigProductMap']/*[##templatename='gojoProductList']");
if (ProductGroup != null)
{
Item[] LocationList = ProductGroup.Axes.SelectItems(#"child::*[##templatename='gojoProductLocation' and #Active = '1']");
if (LocationList != null)
{
DataSet ds = new DataSet();
DataTable locations = ds.Tables.Add("locations");
locations.Columns.Add("LocationName", Type.GetType("System.String"));
locations.Columns.Add("LocationID", Type.GetType("System.String"));
foreach (Item LocationItem in LocationList)
{
DataRow dr = locations.NewRow();
dr["LocationName"] = LocationItem.Fields["Header"].Value;
dr["LocationID"] = LocationItem.ID.ToString();
locations.Rows.Add(dr);
}
locationRepeater.DataSource = ds;
locationRepeater.DataMember = "locations";
locationRepeater.DataBind();
}
}
}
}
}
protected void SetInner(object sender, RepeaterItemEventArgs e)
{
if ((e.Item.ItemType != ListItemType.Footer) & (e.Item.ItemType != ListItemType.Header))
{
Label refID = (Label)e.Item.FindControl("refID");
Label test = (Label)e.Item.FindControl("test");
Repeater areaRepeater = (Repeater)e.Item.FindControl("areaRepeater");
Database db = Sitecore.Context.Database;
Item LocationAreaItem = db.Items[refID.Text];
if (LocationAreaItem != null)
{
Item[] AreaList = LocationAreaItem.Axes.SelectItems(#"child::*[##templatename='gojoProductLocationArea' and #Active = '1']");
if (AreaList != null)
{
DataSet dset = new DataSet();
DataTable areas = dset.Tables.Add("areas");
areas.Columns.Add("AreaName", Type.GetType("System.String"));
areas.Columns.Add("Sku", Type.GetType("System.String"));
areas.Columns.Add("ProductName", Type.GetType("System.String"));
areas.Columns.Add("masterSku", Type.GetType("System.String"));
areas.Columns.Add("masterName", Type.GetType("System.String"));
areas.Columns.Add("Size", Type.GetType("System.String"));
areas.Columns.Add("SkuID", Type.GetType("System.String"));
areas.Columns.Add("AreaID",Type.GetType("System.String"));
areas.Columns.Add("productID", Type.GetType("System.String"));
foreach (Item AreaItem in AreaList)
{
DataRow drow = areas.NewRow();
drow["AreaName"] = AreaItem.Fields["Header"].Value;
drow["AreaID"] = AreaItem.ID.ToString();
areas.Rows.Add(drow);
Item[] SkuList = AreaItem.Axes.SelectItems(#"child::*[(##templatename='gojoPTRefill' or ##templatename = 'gojoPTAccessories' or ##templatename = 'gojoPTDispenser' or ##templatename = 'gojoPTSelfDispensed') and #Active = '1']");
foreach (Item ChildItem in SkuList)
{
Item MarketProduct = db.Items[ChildItem.Fields["Reference SKU"].Value];
drow["productID"] = ChildItem.ID.ToString();
if (MarketProduct != null)
{
Item MasterProduct = db.Items[MarketProduct.Fields["Master Product"].Value];
if (MasterProduct != null)
{
DataRow newRow = areas.NewRow();
if(MasterProduct.TemplateName == "gojoSKUSelfDispensed" || MasterProduct.TemplateName == "gojoSKURefill")
{
newRow["Size"] = MasterProduct.Fields["Size"].Value;
}
else
{
newRow["Size"] = "-";
}
newRow["Sku"] = MasterProduct.Fields["SKU"].Value;
newRow["productID"] = MasterProduct.ID.ToString();
Item MasterProductName = db.Items[MasterProduct.Fields["Complete Product Name"].Value];
if (MasterProductName != null)
{
newRow["ProductName"] = MasterProductName.Fields["Complete Name"].Value;
}
areas.Rows.Add(newRow);
}
}
}
}
areaRepeater.DataSource = dset;
areaRepeater.DataMember = "areas";
areaRepeater.DataBind();
}
}
}
}
protected bool checkQtys(ref int ItemCnt, ref ArrayList LinesToOrder)
{
Repeater locationRepeater = (Repeater)FindControl("locationRepeater");
bool validQtys = true;
string productID = "";
int qty;
qtyErrorMsg.Text = "";
qtyErrorMsgTop.Text = "";
foreach (RepeaterItem repItem in locationRepeater.Items)
{
if (repItem != null)
{
Repeater areaRepeater = (Repeater)repItem.FindControl("areaRepeater");
if (areaRepeater != null)
{
foreach (RepeaterItem skuItm in areaRepeater.Items)
{
if (skuItm != null)
{
Label SkuID = (Label)skuItm.FindControl("SkuID");
Label qtyID = (Label)skuItm.FindControl("qtyID");
PlaceHolder inner = (PlaceHolder)skuItm.FindControl("ProductTable");
if (inner != null)
{
foreach (Control ct in inner.Controls)
{
if (ct is TextBox)
{
TextBox lineQty = (TextBox)ct;
Label prodID = (Label)inner.FindControl("productID");
if (lineQty.Text != "")
{
try
{
int.Parse(lineQty.Text);
productID = prodID.Text;
qty = int.Parse(lineQty.Text);
if (qty > 0)
{
noItemMsg.Visible = false;
noItemMsgTop.Visible = false;
ItemCnt++; //only count items with valid qty values
LinesToOrder.Add(new LineItem(productID, qty));
}
else
{//Qty is 0 or less error
validQtys = false;
qtyErrorMsg.Text = "Quantity must be a number<br />";
qtyErrorMsgTop.Text = "Quantity must be a number<br />";
}
}
catch
{//NaN - display error msg
validQtys = false;
qtyErrorMsg.Text = "Quantity must be a number<br />";
qtyErrorMsgTop.Text = "Quantity must be a number<br />";
}
}
}
}
}
}
}
}
}
}
return validQtys;
}
class LineItem
{//This class will store the product information
public string SKUID;
public int Qty;
public LineItem(string InSKUID, int InQty)
{
this.SKUID = InSKUID;
this.Qty = InQty;
}
}
protected void orderSubmit(object sender, EventArgs e)
{
int ItemCnt = 0;
bool validQtys = true;
ArrayList LinesToOrder = new ArrayList();
Label lb = FindControl("order") as Label;
if (checkQtys(ref ItemCnt,ref LinesToOrder))
{
if (ItemCnt == 0)
{//make sure at least one item with proper qty amount is entered before submitting the order
validQtys = false;
noItemMsg.Visible = true;
noItemMsg.Text = "You must order at least one item<br />";
noItemMsgTop.Visible = true;
noItemMsgTop.Text = "You must order at least one item<br />";
}
if (validQtys)
{//save the information to a session variable and send users to order review page
try
{
foreach (LineItem WorkLine in LinesToOrder)
{
lb.Text += WorkLine.SKUID + ", " + WorkLine.Qty + ";";
}
Session["orderComplete"] = lb.Text;
}
catch (Exception x)
{
Response.Write(x.Message.ToString());
}
Response.Redirect("/united-states/market/office-buildings/obproductmap/OrderReview");
}
}
}
}
Here is the designer code with the repeater that is meant to hold the order summary:
<asp:Repeater ID="orderRepeater" runat="server" >
<headertemplate>
<tr>
<th>SKU</th>
<th>Quantity</th>
</tr>
</headertemplate>
<itemtemplate>
<tr>
<td><%#Eval("sku") %></td>
<td><%#Eval("qty") %></td>
</tr>
</itemtemplate>
</asp:Repeater>
And here is the code behind:
private void Page_Load(object sender, EventArgs e)
{
Item CurrentItem = Sitecore.Context.Item;
Item HomeItem = ScHelper.FindAncestor(CurrentItem, "gojoMarket");
if (Session["orderComplete"] != "")
{
if (HomeItem != null)
{
Item ProductGroup = HomeItem.Axes.SelectSingleItem(#"child::*[##templatename='gojoMarketOfficeBuildigProductMap']/*[##templatename='gojoOrderReview']");
if (ProductGroup != null)
{
//this is where I am confused on how to proceed
}
}
}
}
Everything is working and I did a Response.Write test on the session variable to make sure it had the correct information and it did.
Thanks in advance!
Before I try to address your question, lets take a look at some basics. A Session can hold an object, not just a string object. I would change:
if (Session["orderComplete"] != "")
to
if (Session["orderComplete"] != null && Session["orderComplete"] != "")
if you don't, and Session["orderComplete"] is null, Session["orderComplete"] != "" will throw an error object not set to an instance of an object
And now to your question. Setting your session variable to [sku],[quantity];[sku],[quantity];[sku],[quantity], is not a good idea. For one, its not object oriented and 2, its not going to bind to any repeater or data source. You should create an object and bind a list of those objects to your control:
pseudo code:
class Program
{
static void Main(string[] args)
{
List<Order> orders = new List<Order>();
orders.Add(new Order { Sku = "ABC", Qty = 10});
}
}
public class Order {
public String Sku { get; set; }
public int Qty { get; set; }
}
Then you can bind orders to your repeater. For example:
if (Session["orderComplete"] != null && Session["orderComplete"] != ""){
List<Order> orders = Session["orderComplete"] as List<Order>;
myRepeater.DataSource = orders;
myRepeater.DataBind();
}