My font keep revert to "Times new roman" But I'm I set "Metropolis" in the script - adobe

var parent = app.project.activeItem;
for(var i = 0; i < parent.layers.length; i++){
var mySourceText = parent.layer(i + 1).property("ADBE Text Properties").property("ADBE Text Document");
var textProp = parent.layer(i + 1).property("Source Text");
var currentValue = textProp.value;
if(currentValue.toString().match(/[a-z]/i)){
currentValue.font = "Bodoni-BoldMT";
currentValue.fontSize = 125;
textProp.setValue(currentValue);
$.writeln("alpha hai ", currentValue)
}else if(currentValue.toString().match(/[0-9]/i)){
var myTextDoc = mySourceText.value;
myTextDoc.fontSize = 100;
myTextDoc.font = "Metropolis-Bold";
myTextDoc.fillColor = [0.5,0.5,0];
mySourceText.setValue(myTextDoc);
$.writeln("number hai ", currentValue)
}else if(currentValue.toString().match(/[+\-=]/i)){
currentValue.font = "Times New Roman";
$.writeln("Arrtmathic hai ", currentValue)
}else{
$.writeln("Missed ", currentValue)
}
}

it seems to me that the font name is spelled incorrectly. try to set the necessary one first and pull out all the correct values from it.
enter image description here

Related

First page is blackened after adding watermark

Page is blackened after adding watermark in case of some pdf files . Please see attached image.
What could be the reason , and possible fix.
see the blacked out page image
It does not happen for all the files but for some files only.
Code is here in dotnetfiddle.
var _pdfInBytes = File.ReadAllBytes("c:\\test\\test123.pdf");
string watermarkText = "This watermark text on left side";
var coordinates = new Point(25, 200);
using (var pdfNewDoc = new PdfDocument())
{
using (var pdfImport = PdfReader.Open(new MemoryStream(_pdfInBytes, true), PdfDocumentOpenMode.Import))
{
if (pdfImport.PageCount == 0)
{
return;
}
foreach (var pg in pdfImport.Pages)
{
pdfNewDoc.AddPage(pg);
}
var page = pdfNewDoc.Pages[0];
// overlapping trick #165910
var xOffset = 100.0;
for (var index = 0; index < page.Contents.Elements.Count; index++)
{
var stream = page.Contents.Elements.GetDictionary(index).Stream;
var x = GetMinXOffsetDraft(stream.ToString());
if (xOffset > x)
{
xOffset = x;
}
}
xOffset *= 0.6; // magic number :)
// blank page trick #165910
if (page.CropBox.IsEmpty && !page.MediaBox.IsEmpty)
{
page.CropBox = page.MediaBox;
}
// Get an XGraphics object for drawing beneath the existing content
var gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);
var tf = new XTextFormatter(gfx);
var xFont = new XFont("Arial", 10, XFontStyle.Regular);
// Get watermark text size
var wmSize = gfx.MeasureString(watermarkText, xFont);
// Middle Y coordinate
var wmY = (gfx.PageSize.Height - wmSize.Width) / 2;
var coords = new XPoint(page.CropBox.Location.X + (xOffset < coordinates.X ? xOffset : coordinates.X),
page.CropBox.Location.Y + (coordinates.Y > wmY ? coordinates.Y : wmY));
// Define a rotation transformation at the center of the page
gfx.TranslateTransform(coordinates.X, coordinates.Y);
gfx.RotateTransform(90);
gfx.TranslateTransform(-coordinates.X, -coordinates.Y);
// Create brush
var brushColor = Color.Red;
var brush1= new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
brush1.Overprint = false;
XBrush brush =
new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
var rect = new XRect(coordinates.X, coordinates.Y, gfx.PageSize.Height - coordinates.Y,
coordinates.X);
tf.DrawString(watermarkText, xFont, brush, rect);
byte[] outputBytes = null;
using (var outStream = new MemoryStream())
{
pdfNewDoc.Save(outStream, false);
outputBytes = outStream.ToArray();
}
File.WriteAllBytes("c:\\test\\test-"+DateTime.Now.ToString("ddmmyyyyhhmmss") +".pdf", outputBytes);
private double GetMinXOffsetDraft(string v)
{
var result = 100.0;
using (var str = new StringReader(v))
{
var s = str.ReadLine();
do
{
var sarr = s?.Split(' ');
if (sarr?.Length == 7 && sarr[6] == "Tm")
{
var x = double.Parse(sarr[4]);
x = x < 0 ? 200 : x;
result = result > x ? x : result;
}
s = str.ReadLine();
} while (s != null);
}
return result;
} var _pdfInBytes = File.ReadAllBytes("c:\\test\\test123.pdf");
string watermarkText = "This watermark text on left side";
var coordinates = new Point(25, 200);
using (var pdfNewDoc = new PdfDocument())
{
using (var pdfImport = PdfReader.Open(new MemoryStream(_pdfInBytes, true), PdfDocumentOpenMode.Import))
{
if (pdfImport.PageCount == 0)
{
return;
}
foreach (var pg in pdfImport.Pages)
{
pdfNewDoc.AddPage(pg);
}
var page = pdfNewDoc.Pages[0];
// overlapping trick #165910
var xOffset = 100.0;
for (var index = 0; index < page.Contents.Elements.Count; index++)
{
var stream = page.Contents.Elements.GetDictionary(index).Stream;
var x = GetMinXOffsetDraft(stream.ToString());
if (xOffset > x)
{
xOffset = x;
}
}
xOffset *= 0.6; // magic number :)
// blank page trick #165910
if (page.CropBox.IsEmpty && !page.MediaBox.IsEmpty)
{
page.CropBox = page.MediaBox;
}
// Get an XGraphics object for drawing beneath the existing content
var gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);
var tf = new XTextFormatter(gfx);
var xFont = new XFont("Arial", 10, XFontStyle.Regular);
// Get watermark text size
var wmSize = gfx.MeasureString(watermarkText, xFont);
// Middle Y coordinate
var wmY = (gfx.PageSize.Height - wmSize.Width) / 2;
var coords = new XPoint(page.CropBox.Location.X + (xOffset < coordinates.X ? xOffset : coordinates.X),
page.CropBox.Location.Y + (coordinates.Y > wmY ? coordinates.Y : wmY));
// Define a rotation transformation at the center of the page
gfx.TranslateTransform(coordinates.X, coordinates.Y);
gfx.RotateTransform(90);
gfx.TranslateTransform(-coordinates.X, -coordinates.Y);
// Create brush
var brushColor = Color.Red;
var brush1= new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
brush1.Overprint = false;
XBrush brush =
new XSolidBrush(XColor.FromArgb(brushColor.A, brushColor.R, brushColor.G, brushColor.B));
var rect = new XRect(coordinates.X, coordinates.Y, gfx.PageSize.Height - coordinates.Y,
coordinates.X);
tf.DrawString(watermarkText, xFont, brush, rect);
byte[] outputBytes = null;
using (var outStream = new MemoryStream())
{
pdfNewDoc.Save(outStream, false);
outputBytes = outStream.ToArray();
}
File.WriteAllBytes("c:\\test\\test-"+DateTime.Now.ToString("ddmmyyyyhhmmss") +".pdf", outputBytes);
private double GetMinXOffsetDraft(string v)
{
var result = 100.0;
using (var str = new StringReader(v))
{
var s = str.ReadLine();
do
{
var sarr = s?.Split(' ');
if (sarr?.Length == 7 && sarr[6] == "Tm")
{
var x = double.Parse(sarr[4]);
x = x < 0 ? 200 : x;
result = result > x ? x : result;
}
s = str.ReadLine();
} while (s != null);
}
return result;
}

Trouble integrating Woocommerce order details into Google Sheet with Google App Script API

I have an API that automatically pulls new order details from my Woocommerce store into a Google Sheet. It seems to be working however, it has failed to pull the first 7 orders into my google sheet. It has all of the orders after the first 7. How do I get it to pull the first 7 orders into the sheet?
Here is my Google App Script:
function start_sync() {
// Followed instructions at https://github.com/mithunmanohar/woocommerce-orders-google-sheets-integration
var sheet_name = "OrderDetails"
update_order_5_min(sheet_name)
}
function update_order_5_min(sheet_name) {
var ck = "ck_ed82fae51e5bafce28dde95224db9c9c4bd36dba";
var cs = "cs_9a16fd7b641769a65412f336de3e7a928f7e153c";
var website = "https://www.funtrackdayz.com";
var now = new Date();
var website_t ="240";
var min = website_t * 60
now.setMinutes(now.getMinutes() - min);
var n = now.toISOString();
var surl = website + "/wc-api/v3/orders?consumer_key=" + ck + "&consumer_secret=" + cs + "&status=processing&filter[created_at_min]=" + n //"&after=2016-10-27T10:10:10Z"
// var surl = website + "/wc-api/v3/orders?consumer_key=" + ck + "&consumer_secret=" + cs + "&status=processing"
// &filter[created_at_min]=" + n //"&after=2016-10-27T10:10:10Z"
var url = surl
var options = {
"method": "GET",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"muteHttpExceptions": true,
};
var result = UrlFetchApp.fetch(url, options);
if (result.getResponseCode() == 200) {
var params = JSON.parse(result.getContentText());
}
var doc = SpreadsheetApp.getActiveSpreadsheet();
var temp = doc.getSheetByName(sheet_name);
var consumption = {}
//"orders"
arrayLength = params["orders"].length
for (var i = 0; i < arrayLength; i++) {
var container = [];
a = container.push(params["orders"][i]["billing_address"]["first_name"]);
a = container.push(params["orders"][i]["billing_address"]["last_name"]);
a = container.push(params["orders"][i]["billing_address"]["address_1"] + ", " + params["orders"][i]["billing_address"]["address_2"]);
a = container.push("");
a = container.push(params["orders"][i]["billing_address"]["city"]);
a = container.push(params["orders"][i]["billing_address"]["state"]);
a = container.push(params["orders"][i]["billing_address"]["postcode"]);
a = container.push(params["orders"][i]["billing_address"]["phone"]);
a = container.push(params["orders"][i]["billing_address"]["email"]);
a = container.push(params["orders"][i]["total"]); //price
a = container.push(params["orders"][i]["payment_details"]["method_id"]);
c = params["orders"][i]["line_items"].length;
items = "";
skus="";
for (var k = 0; k < c; k++) {
item = params["orders"][i]["line_items"][k]["name"];
qty = params["orders"][i]["line_items"][k]["quantity"];
sku = params["orders"][i]["line_items"][k]["sku"];
meta = ""
try {
meta = params["orders"][i]["line_items"][k]["meta"][0]["value"];
meta = " - " + meta
} catch (err) {
meta = ""
}
item_f = qty + " x " + item + meta
items = items + item_f + ",\n"
skus = skus + ",\n"
}
a = container.push(items)
a = container.push(sku)
// a = container.push(params["orders"][i]["total_line_items_quantity"]); // Quantity
a = container.push(params["orders"][i]["order_number"]); //
a = container.push(params["orders"][i]["note"])
a = container.push(params["orders"][i]["created_at"]);
var doc = SpreadsheetApp.getActiveSpreadsheet();
var temp = doc.getSheetByName(sheet_name);
temp.appendRow(container);
removeDuplicates(sheet_name)
}
}
function removeDuplicates(sheet_name) {
var doc = SpreadsheetApp.getActiveSpreadsheet();
var sheet = doc.getSheetByName(sheet_name);
var data = sheet.getDataRange().getValues();
var newData = new Array();
for (i in data) {
var row = data[i];
var duplicate = false;
for (j in newData) {
if (row.join() == newData[j].join()) {
duplicate = true;
}
}
if (!duplicate) {
newData.push(row);
}
}
sheet.clearContents();
sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}

EPPlus ColumnStacked chart data point colors

I am able to generate Column Stacked chart using EPPlus. There is is requirement to change the color of datapoint.
I found the solution of at enter link description here but it only changes the color of first datapoint of the series. Can I get help to change the color of other datapoints as well. Here is the concept that I am looking for enter image description here
Here is the function that helps to change datapoint first color
public void SetDataPointStyle(OfficeOpenXml.Drawing.Chart.ExcelChart chart, ExcelChartSerie series, int totalDataPoint, Color color)
{
var i = 0;
var found = false;
foreach (var s in chart.Series)
{
if (s == series)
{
found = true;
break;
}
++i;
}
if (!found) throw new InvalidOperationException("series not found.");
var nsm = chart.WorkSheet.Drawings.NameSpaceManager;
var nschart = nsm.LookupNamespace("c");
var nsa = nsm.LookupNamespace("a");
var node = chart.ChartXml.SelectSingleNode(#"c:chartSpace/c:chart/c:plotArea/c:barChart/c:ser[c:idx[#val='" + i.ToString(System.Globalization.CultureInfo.InvariantCulture) + "']]", nsm);
var doc = chart.ChartXml;
var spPr = doc.CreateElement("c:spPr", nschart);
var solidFill = spPr.AppendChild(doc.CreateElement("a:solidFill", nsa));
var srgbClr = solidFill.AppendChild(doc.CreateElement("a:srgbClr", nsa));
var valattrib = srgbClr.Attributes.Append(doc.CreateAttribute("val"));
valattrib.Value = ToHex(color).Substring(1);
//var ln = spPr.AppendChild(doc.CreateElement("a:ln", nsa));
//var lnSolidFill = ln.AppendChild(doc.CreateElement("a:solidFill", nsa));
//var lnSrgbClr = lnSolidFill.AppendChild(doc.CreateElement("a:srgbClr", nsa));
//var lnValattrib = lnSrgbClr.Attributes.Append(doc.CreateAttribute("val"));
//lnValattrib.Value = ToHex(Color.Gray).Substring(1);
node.AppendChild(spPr);
}
public String ToHex(Color c)
{
return "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
}
SetDataPointStyle(chart, chart.Series[0], 1, Color.Tan);
You have to populate a series of data point colors per series. Here is an extension method that will set the series data points to random colors. Just have to specify the serie number. If pick your own colors just override the logic or send in an array to use:
public static void SetChartPointRandomColors(this ExcelChart chart, int serieNumber)
{
var chartXml = chart.ChartXml;
var nsa = chart.WorkSheet.Drawings.NameSpaceManager.LookupNamespace("a");
var nsuri = chartXml.DocumentElement.NamespaceURI;
var nsm = new XmlNamespaceManager(chartXml.NameTable);
nsm.AddNamespace("a", nsa);
nsm.AddNamespace("c", nsuri);
var serieNode = chart.ChartXml.SelectSingleNode(#"c:chartSpace/c:chart/c:plotArea/c:barChart/c:ser[c:idx[#val='" + serieNumber + "']]", nsm);
var serie = chart.Series[serieNumber];
var points = serie.Series.Length;
var rand = new Random(serieNumber);
for (var i = 1; i <= points; i++)
{
var dPt = chartXml.CreateNode(XmlNodeType.Element, "dPt", nsuri);
var idx = chartXml.CreateNode(XmlNodeType.Element, "idx", nsuri);
var att = chartXml.CreateAttribute("val", nsuri);
att.Value = i.ToString();
idx.Attributes.Append(att);
dPt.AppendChild(idx);
var srgbClr = chartXml.CreateNode(XmlNodeType.Element, "srgbClr", nsa);
att = chartXml.CreateAttribute("val");
//Generate a random color - override with own logic to specify
var color = Color.FromArgb(rand.Next(256), rand.Next(256), rand.Next(256));
att.Value = $"{color.R:X2}{color.G:X2}{color.B:X2}";
srgbClr.Attributes.Append(att);
var solidFill = chartXml.CreateNode(XmlNodeType.Element, "solidFill", nsa);
solidFill.AppendChild(srgbClr);
var spPr = chartXml.CreateNode(XmlNodeType.Element, "spPr", nsuri);
spPr.AppendChild(solidFill);
dPt.AppendChild(spPr);
serieNode.AppendChild(dPt);
}
}
Here is an example of usage:
[TestMethod]
public void Chart_BarChart_Colors_Test()
{
//Throw in some data
var datatable = new DataTable("tblData");
datatable.Columns.AddRange(new[]{new DataColumn("Col1", typeof(int)),new DataColumn("Col2", typeof(int)),new DataColumn("Col3", typeof(int))});
for (var i = 0; i < 10; i++){var row = datatable.NewRow();row[0] = i;row[1] = i * 10;row[2] = i * 15;datatable.Rows.Add(row);}
//Create a test file
var fileInfo = new FileInfo(#"c:\temp\Chart_BarChart_Colors.xlsx");
if (fileInfo.Exists)
fileInfo.Delete();
using (var pck = new ExcelPackage(fileInfo))
{
var workbook = pck.Workbook;
var worksheet = workbook.Worksheets.Add("Sheet1");
worksheet.Cells.LoadFromDataTable(datatable, true);
var chart = worksheet.Drawings.AddChart("chart test", eChartType.ColumnStacked);
chart.Series.Add(worksheet.Cells["B2:B11"], worksheet.Cells["A2:A11"]);
chart.Series.Add(worksheet.Cells["C2:C11"], worksheet.Cells["A2:A11"]);
chart.SetChartPointRandomColors(0);
chart.SetChartPointRandomColors(1);
pck.Save();
}
}
Will give you this:
I had a similar use case, I needed to set the color of a slice (datapoint) of a doughnut chart. This question/answer helped immensely and I figured I would share the result in case anyone else hits this issue.
Note 1: I am using C# 9 with nullability enabled; you can remove the !'s if you aren't using nullability.
Note 2: I have no use case for multiple series in a doughnut chart, so this is hardcoded to series 0. You can parameterize the SelectSingleNode index if this doesn't work for you.
public void SetDoughnutChartDataPointFill(ExcelChart chart, int dataPointIdx, Color color)
{
var nsm = chart.WorkSheet.Drawings.NameSpaceManager;
var nschart = nsm.LookupNamespace("c");
var nsa = nsm.LookupNamespace("a");
var node = chart.ChartXml.SelectSingleNode(#"c:chartSpace/c:chart/c:plotArea/c:doughnutChart/c:ser[c:idx[#val='0']]", nsm)!;
var doc = chart.ChartXml;
var dPt = doc.CreateElement("c:dPt", nschart);
var cdpIdx = doc.CreateElement("c:idx", nschart);
var valattr = cdpIdx.Attributes!.Append(doc.CreateAttribute("val"));
valattr.Value = dataPointIdx.ToString();
dPt.AppendChild(cdpIdx);
var spPr = doc.CreateElement("c:spPr", nschart);
var solidFill = spPr.AppendChild(doc.CreateElement("a:solidFill", nsa))!;
var srgbClr = solidFill.AppendChild(doc.CreateElement("a:srgbClr", nsa))!;
var valattrib = srgbClr.Attributes!.Append(doc.CreateAttribute("val"));
valattrib.Value = string.Format("{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);
dPt.AppendChild(spPr);
node.AppendChild(dPt);
}

Create a custom legend in tabular format - ASP.NET Chart

I am quite new to ASP.NET Charting and have a question about adding custom component to a bar chart. I am trying to create a custom legend in a tabular format. What I mean is my legend style is table. And I am creating each LegendItem from database values and adding it to chart.Legends[0].CustomItems collection.
I get the data but I am getting all the LegendItems in one row. I want to display each LegendItem on new row. My current code look like this -
chart.Legends.Add(new Legend
{
LegendStyle = LegendStyle.Table,
BorderColor = Color.Black,
BorderWidth = 1,
BorderDashStyle = ChartDashStyle.Solid,
Alignment = StringAlignment.Center,
DockedToChartArea = areaCounter.ToString(),
Docking = Docking.Bottom,
Name = "CustomLegend",
IsTextAutoFit = true,
InterlacedRows = true,
TableStyle = LegendTableStyle.Auto,
IsDockedInsideChartArea = false
});
LegendItem newItem = new LegendItem();
newItem.Cells.Add(LegendCellType.Text, " - value1 - ", ContentAlignment.MiddleCenter);
newItem.Cells.Add(LegendCellType.Text, " - State Average = - ", ContentAlignment.MiddleCenter);
newItem.Cells[1].CellSpan = 2;
newItem.BorderColor = Color.Black;
newItem.Cells.Add(LegendCellType.Text, " - ", ContentAlignment.MiddleCenter);
newItem.Cells.Add(LegendCellType.Text, " - top - ", ContentAlignment.MiddleCenter);
chart.Legends[1].CustomItems.Add(newItem);
LegendItem newItem1 = new LegendItem();
newItem1.Cells.Add(LegendCellType.Text, "value1", ContentAlignment.MiddleCenter);
newItem1.Cells.Add(LegendCellType.Text, "State Average =", ContentAlignment.MiddleCenter);
newItem1.Cells[1].CellSpan = 2;
newItem1.BorderColor = Color.Black;
newItem1.Cells.Add(LegendCellType.Text, "", ContentAlignment.MiddleCenter);
newItem1.Cells.Add(LegendCellType.Text, "top", ContentAlignment.MiddleCenter);
chart.Legends[1].CustomItems.Add(newItem1);
newItem and newItem1 both appear on same row as legend. Can you please help me solve this issue ? I'd really appreciate your help.
Found out that once I add HeaderSeparator to my custom Legend object and handle the chat object's CustomizeLegend event it worked as I wanted. The custom items are displayed on separate rows. Here are the changes that I did.
chart.Legends.Add(new Legend
{
LegendStyle = LegendStyle.Table,
BorderColor = Color.Black,
BorderWidth = 1,
BorderDashStyle = ChartDashStyle.Solid,
Alignment = StringAlignment.Center,
DockedToChartArea = areaCounter.ToString(),
Docking = Docking.Bottom,
Name = "CustomLegend",
IsTextAutoFit = true,
InterlacedRows = true,
TableStyle = LegendTableStyle.Tall,
HeaderSeparator = LegendSeparatorStyle.Line,
HeaderSeparatorColor = Color.Gray,
IsDockedInsideChartArea = false
});
LegendItem newItem3 = new LegendItem();
var strVal = item.Value;
foreach (var val in strVal)
{
newItem3.Cells.Add(LegendCellType.Text, val, ContentAlignment.BottomCenter);
}
chart.Legends["CustomLegend"].CustomItems.Add(newItem3);
chart.CustomizeLegend += chart_CustomizeLegend;
void chart_CustomizeLegend(object sender, CustomizeLegendEventArgs e)
{
Chart chart = sender as Chart;
if (chart == null) return;
foreach (var item in e.LegendItems)
{
item.SeparatorType = LegendSeparatorStyle.Line;
item.SeparatorColor = Color.Black;
}
}

Get Data from a table which has been generated programmatically

I am creating a Control Table programmatically and I want after user clicks a button to get the values.
The table has three columns, {Title(DropDownList), FName(TextBox), LName(TextBox)} and two rows.
I am getting the values for FName, LName without problem, but I am getting wrong value for Title, which is a DropDownList. It gives me for both Titles, the selected value of the second column.
More Clear,
For the 1st row --> Mr, Foo, Bar
for 2nd row- -> Mrs, Foo, Bar
after user clicks the button I am getting
For 1st row --> Mrs, Foo, Bar
For 2nd row- -> Mrs, Foo1, Bar.
This is the method of table creation
private void SetPassengerDetailsTable(int roomIdentity, int? adults,
int? children, int? infants, bool setLeader = false) {
var leaderIsSet = false;
var roomTable = new Table();
roomTable.ID = "PassengerDetailsTBL_" + roomIdentity;
var trHeader = new TableHeaderRow();
var tcTitle = new TableCell();
tcTitle.Controls.Add(new Label() { Text = "<b>Title</b>" });
trHeader.Cells.Add(tcTitle);
var tcFName = new TableCell();
tcFName.Controls.Add(new Label() { Text = "<b>First Name</b>" });
trHeader.Cells.Add(tcFName);
var tcLName = new TableCell();
tcLName.Controls.Add(new Label() { Text = "<b>Last Name</b>" });
trHeader.Cells.Add(tcLName);
var tcType = new TableCell();
tcType.Controls.Add(new Label() { Text = "<bType</b>" });
trHeader.Cells.Add(tcType);
roomTable.Rows.Add(trHeader);
var listItems = new ListItem[6];
listItems[0] = new ListItem("", "") { Selected = true };
listItems[1] = new ListItem("Mr", "Mr");
listItems[2] = new ListItem("Mrs", "Mrs");
listItems[3] = new ListItem("Miss", "Miss");
listItems[4] = new ListItem("Infant", "Inf");
listItems[5] = new ListItem("Child", "Master");
if (adults != null || adults > 0) {
for (int i = 1; i <= adults; i++) {
var trBody = new TableRow();
var ddl = new DropDownList();
var leadAdultRowID = setLeader && !leaderIsSet ? "leadadult" : "adult";
ddl.ID = "room" + roomIdentity + leadAdultRowID + i + "Title";
ddl.Items.AddRange(listItems);
var tcTitleValue = new TableCell();
tcTitleValue.Controls.Add(ddl);
trBody.Cells.Add(tcTitleValue);
var tcFNameValue = new TableCell();
tcFNameValue.Controls.Add(new TextBox() { ID = "room" + roomIdentity + "adult" + i + "FName", Width = 170 });
trBody.Cells.Add(tcFNameValue);
var tcLNameValue = new TableCell();
tcLNameValue.Controls.Add(new TextBox() { ID = "room" + roomIdentity + "adult" + i + "LName", Width = 170 });
trBody.Cells.Add(tcLNameValue);
var tcTypeValue = new TableCell();
var leadAdult = setLeader && !leaderIsSet ? "Lead Adult" : "Adult";
tcTypeValue.Controls.Add(new Label() { Text = leadAdult });
trBody.Cells.Add(tcTypeValue);
roomTable.Rows.Add(trBody);
if (setLeader)
leaderIsSet = true;
}
}
if (children != null || children > 0) {
for (int i = 1; i <= children; i++) {
var trBody = new TableRow();
var ddl = new DropDownList();
ddl.ID = "room" + roomIdentity + "child" + i + "Title";
ddl.Items.AddRange(listItems);
var tcTitleValue = new TableCell();
tcTitleValue.Controls.Add(ddl);
trBody.Cells.Add(tcTitleValue);
var tcFNameValue = new TableCell();
tcFNameValue.Controls.Add(new TextBox() { ID = "room" + roomIdentity + "child" + i + "FName", Width = 170 });
trBody.Cells.Add(tcFNameValue);
var tcLNameValue = new TableCell();
tcLNameValue.Controls.Add(new TextBox() { ID = "room" + roomIdentity + "child" + i + "LName", Width = 170 });
trBody.Cells.Add(tcLNameValue);
var tcTypeValue = new TableCell();
tcTypeValue.Controls.Add(new Label() { Text = "Child" });
trBody.Cells.Add(tcTypeValue);
roomTable.Rows.Add(trBody);
}
}
if (infants != null || infants > 0) {
for (int i = 1; i <= infants; i++) {
var trBody = new TableRow();
var ddl = new DropDownList();
ddl.ID = "room" + roomIdentity + "infan" + i + "Title";
ddl.Items.AddRange(listItems);
var tcTitleValue = new TableCell();
tcTitleValue.Controls.Add(ddl);
trBody.Cells.Add(tcTitleValue);
var tcFNameValue = new TableCell();
tcFNameValue.Controls.Add(new TextBox() { ID = "room" + roomIdentity + "infan" + i + "FName", Width = 170 });
trBody.Cells.Add(tcFNameValue);
var tcLNameValue = new TableCell();
tcLNameValue.Controls.Add(new TextBox() { ID = "room" + roomIdentity + "infan" + i + "LName", Width = 170 });
trBody.Cells.Add(tcLNameValue);
var tcTypeValue = new TableCell();
tcTypeValue.Controls.Add(new Label() { Text = "Infant" });
trBody.Cells.Add(tcTypeValue);
roomTable.Rows.Add(trBody);
}
}
PassengerDetailsPH.Controls.Add(roomTable);
}
Thanks
Double check what client-side IDs are generated for your drop downs.
If you table is rendered correctly (with correct IDs which must be unique), then the code which reads is reading from the wrong element.
create a new listItems list for every instance of the DropDownList
var ddlItems = listItems.ToArray();
ddl.Items.Addrange(ddlItems);
(have you looked at the GridView control?)

Resources