Store list of hyperlinks - asp.net

I have an aspx page that contains a grid-view. The data-source for the gird-view is a datatable.
I want the last column in the grid view to contain a list of hyperlinks. I cannot figure out how to store or display this data
private void retrieveGroups()
{
// UserTab is a DataTable
// UserGrid is a GridView
UserTab.Columns.Add("LoginName", typeof(string));
UserTab.Columns.Add("DisplayName", typeof(string));
UserTab.Columns.Add("Kind", typeof(string));
UserTab.Columns.Add("Count", typeof(string));
UserTab.Columns.Add("Managers", typeof(string));
UserGrid.DataSource = UserTab;
SqlCommand cmd = FmaDb.makeCmd(FmaDb.SubDB.FMA_CUSTOMER, "fetchGroupIds", CommandType.StoredProcedure,
delegate(SqlCommand inCmd) { inCmd.Parameters.Add("#siteid", SqlDbType.Int); });
List<int> groupIds = new List<int>();
FmaDb.runReadCmd(cmd, delegate(SqlCommand inCmd) { inCmd.Parameters["#siteid"].Value = int.Parse(LFList.SelectedItem.Value); }, null,
delegate(SqlDataReader qrdr) { groupIds.Add(FmaDb.getDbInt(qrdr, 0)); });
UserGrid.Visible = true;
HyperLinkField hf = new HyperLinkField();
BoundField bf = new BoundField();
hf.HeaderText = "Login";
hf.DataTextField = "LoginName";
hf.DataNavigateUrlFields = new String[1] { "login" };
hf.DataNavigateUrlFormatString = "~/fausage.aspx?cn=login&lg={0}&ad=" + ad + "&as=" + aStatus;
UserGrid.Columns.Add(hf);
bf = new BoundField();
bf.HeaderText = "Name";
bf.DataField = "DisplayName";
UserGrid.Columns.Add(bf);
bf = new BoundField();
bf.HeaderText = "Type";
bf.DataField = "Kind";
UserGrid.Columns.Add(bf);
bf = new BoundField();
bf.HeaderText = "# Members";
bf.DataField = "Count";
UserGrid.Columns.Add(bf);
bf = new BoundField();
bf.HeaderText = "Managers";
bf.DataField = "Managers";
UserGrid.Columns.Add(bf);
foreach (int gId in groupIds)
{
Advisor advGroup = new Advisor(gId);
List<HyperLink> linkList = new List<HyperLink>();
advGroup.fetch();
if ((advGroup.Kind == AdvisorKind.Branch) || (advGroup.Kind == AdvisorKind.Team))
{
List<AdvisorMembership> members = advGroup.MyMembers(null, false);
if (advGroup.Kind == AdvisorKind.Branch)
{
List<AdvisorMembership> mgrs = advGroup.MyMembers(null, true);
HyperLink link;
foreach (AdvisorMembership m in mgrs)
{
if (m.MemberCanLoginAsContainer)
{
link = new HyperLink();
link.Text = m.Member.LoginName;
link.NavigateUrl = "~/fausage.aspx?cn=login&lg=" + m.Member.LoginName + "&ad=" + ad + "&as=" + aStatus;
link.Target = "blank";
linkList.Add(link);
}
}
}
UserTab.Rows.Add(advGroup.LoginName, advGroup.DisplayName, advGroup.Kind.ToString(), members.Count.ToString(), linkList);
}
ViewState["DataTable"] = UserTab;
}
}
}
}

Related

Unable to update the textbox values in the gridview[c# asp.net]

Getting old values in DataTable, I need new values which I updated. Please help me?
Update on button click
My code:
DataSet Ds = new DataSet();
string Query = "";
Query = "select Conv_0,Unit_0,Rate_0,Text_0,Barcode_0,Conv_1,Unit_1,Rate_1,Text_1,Barcode_1,Conv_2,Unit_2,Rate_2,Text_2,Barcode_2,Conv_3,Unit_3,Rate_3,Text_3,Barcode_3,Conv_4,Unit_4,Rate_4,Text_4,Barcode_4 from Prod_Unit where Code='" + a + "'";
Ds = SqlClass1.GetData_from_localhost(Query);
if (Ds.Tables[0].Rows.Count > 0)
{
dt.Columns.Clear();
dt.Rows.Clear();
dt.Columns.Add("NO");
dt.Columns.Add("UNITS");
dt.Columns.Add("CONVERSION");
dt.Columns.Add("BARCODE");
dt.Columns.Add("RATE 1");
dt.Columns.Add("RATE 2");
dt.Columns.Add("PRINT TEXT");
// dt.Rows.Add();
for (int i = 0; i < Ds.Tables[0].Columns.Count; i++)
{
if (i >= 0 && i <= 4)
{
dt.Rows.Add();
dt.Rows[i]["NO"] = i + 1;
string unit = Ds.Tables[0].Rows[0]["Unit_" + i + ""].ToString();
DataSet temp = SqlClass1.GetData_from_localhost("select Unit FROM Units where Code=" + unit + "");
if (temp.Tables[0].Rows.Count > 0)
{
dt.Rows[i]["UNITS"] = temp.Tables[0].Rows[0][0].ToString();
}
dt.Rows[i]["CONVERSION"] = Ds.Tables[0].Rows[0]["Conv_" + i + ""].ToString();
dt.Rows[i]["BARCODE"] = Ds.Tables[0].Rows[0]["Barcode_" + i + ""].ToString();
dt.Rows[i]["RATE 1"] = Ds.Tables[0].Rows[0]["Rate_" + i + ""].ToString();
dt.Rows[i]["RATE 2"] = Ds.Tables[0].Rows[0]["Rate_" + i + ""].ToString();
dt.Rows[i]["PRINT TEXT"] = Ds.Tables[0].Rows[0]["Text_" + i + ""].ToString();
}
}
if (i == 0)
{
// ViewState["CurrentTable"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
// SetPreviousData();
}
}
ViewState["CurrentTable"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
SetPreviousData();// function to get previous data in
textbox
This is my binding function that I call in postback. How can I get updated values in ViewState["CurrentTable"] = dt;
on Update Button
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("NO");
dt.Columns.Add("UNITS");
dt.Columns.Add("CONVERSION");
dt.Columns.Add("BARCODE");
dt.Columns.Add("RATE 1");
dt.Columns.Add("RATE 2");
dt.Columns.Add("PRINT TEXT");
dr = dt.NewRow();
dr["NO"] = 1;
dr["UNITS"] = string.Empty;
dr["CONVERSION"] = string.Empty;
dr["BARCODE"] = string.Empty;
dr["RATE 1"] = string.Empty;
dr["RATE 2"] = string.Empty;
dr["PRINT TEXT"] = string.Empty;
dt.Rows.Add(dr);
int rowIndex = 0;
for (int i = 0; i < GridView1.Rows.Count; i ++)
{
if (GridView1.Rows[rowIndex].RowType == DataControlRowType.DataRow)
{
DropDownList box1 = (DropDownList)GridView1.Rows[rowIndex].Cells[1].FindControl("DropDownList1");
TextBox box2 = (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
TextBox box4 = (TextBox)GridView1.Rows[rowIndex].Cells[4].FindControl("TextBox4");
TextBox box5 = (TextBox)GridView1.Rows[rowIndex].Cells[5].FindControl("TextBox5");
TextBox box6 = (TextBox)GridView1.Rows[rowIndex].Cells[6].FindControl("TextBox6");
dt.Rows[i]["NO"] = i + 1;
dt.Rows[i]["Units"] = box1.Text;
dt.Rows[i]["Conversion"] = box2.Text;
dt.Rows[i]["Barcode"] = box3.Text;
dt.Rows[i]["Rate 1"] = box4.Text;
dt.Rows[i]["Rate 2"] = box5.Text;
dt.Rows[i]["Print Text"] = box6.Text;
dt.Rows.Add();
rowIndex++;
}
}
ViewState["CurrentTable"] = dt;
Save();//function for save
}

how to add button in Dynamic gridview?

public void BuildMeatTally()
{
try
{
DataTable dtdate = new DataTable();
objRetailPL.status = 4;
dtdate = objRetailBAL.GetTypeNew(objRetailPL);
if (dtdate.Rows.Count > 0)
{
for (int i = 0; i < dtdate.Rows.Count; i++)
{
string branchdate;
int totbirds; float totwt, meatyield, Avgweight;
DateTime datewr;
DataTable dtdatedetailsTable = new DataTable();
objRetailPL.branchdate = dtdate.Rows[i]["BranchDate"].ToString();
objRetailPL.sno = Convert.ToInt32(dtdate.Rows[i]["sno"].ToString());
dtdatedetailsTable = objRetailBAL.getbradisdatewisedet(objRetailPL);
branchdate = dtdatedetailsTable.Rows[0]["BranchDate"].ToString();
totbirds = Convert.ToInt32(dtdatedetailsTable.Rows[0]["numofbirds"].ToString());
totwt = Convert.ToSingle(dtdatedetailsTable.Rows[0]["totalweght"].ToString());
meatyield = Convert.ToSingle(dtdatedetailsTable.Rows[0]["totalmeatyeild"].ToString());
Avgweight = Convert.ToSingle(dtdatedetailsTable.Rows[0]["AvgWeight"].ToString());
Table tbldynamic = new Table();
tbldynamic.BorderStyle = BorderStyle.Ridge;
tbldynamic.Width = 600;
TableCell tc = new TableCell();
TableRow tr = new TableRow();
Label lblbranchdate = new Label();
lblbranchdate.ID = "lblbrandate" + i.ToString();
lblbranchdate.Text = "&nbsp&nbsp" + "<B>Branch Date:</B>" + "&nbsp";
tc.Controls.Add(lblbranchdate);
Label lblbranchdatedata = new Label();
lblbranchdatedata.ID = "lbltotnumbird1" + i.ToString();
lblbranchdatedata.Text = branchdate + "&nbsp&nbsp&nbsp";
tc.Controls.Add(lblbranchdatedata);
tr.Cells.Add(tc);
tbldynamic.Rows.Add(tr);
Label lbltotwt1 = new Label();
lbltotwt1.ID = "lbltotwt1" + i.ToString();
lbltotwt1.Text = "<B>Total Weight:</B>" + "&nbsp";
tc.Controls.Add(lbltotwt1);
Label lbltotwt1data = new Label();
lbltotwt1data.ID = "lbltotwt1data" + i.ToString();
lbltotwt1data.Text = totwt + "&nbsp&nbsp&nbsp";
tc.Controls.Add(lbltotwt1data);
tr.Cells.Add(tc);
tbldynamic.Rows.Add(tr);
tc = new TableCell();
tr = new TableRow();
Label lbltotbirds = new Label();
lbltotbirds.ID = "lbltotbird" + i.ToString();
lbltotbirds.Text = "<B>Total Birds:</B>" + "&nbsp";
tc.Controls.Add(lbltotbirds);
Label lbltotbirddata = new Label();
lbltotbirddata.ID = "lbltotbirdata" + i.ToString();
lbltotbirddata.Text = totbirds + "&nbsp&nbsp&nbsp";
tc.Controls.Add(lbltotbirddata);
tr.Cells.Add(tc);
tbldynamic.Rows.Add(tr);
Label lblmeatyield = new Label();
lblmeatyield.ID = "lblmeatyield" + i.ToString();
lblmeatyield.Text = "<B>Meat Yield in Kgs:</B>" + "&nbsp";
tc.Controls.Add(lblmeatyield);
Label lblmeatyielddata = new Label();
lblmeatyielddata.ID = "lblmeatyied" + i.ToString();
lblmeatyielddata.Text = meatyield + "&nbsp&nbsp&nbsp";
tc.Controls.Add(lblmeatyielddata);
tr.Cells.Add(tc);
tbldynamic.Rows.Add(tr);
Label lblavgweight = new Label();
lblavgweight.ID = "lblavgweight" + i.ToString();
lblavgweight.Text = "<B>Avg Weight:</B>" + "&nbsp";
tc.Controls.Add(lblavgweight);
Label lblavgweightdata = new Label();
lblavgweightdata.ID = "lblavgweightdata" + i.ToString();
lblavgweightdata.Text = Avgweight + "&nbsp&nbsp&nbsp";
tc.Controls.Add(lblavgweightdata);
tr.Cells.Add(tc);
tbldynamic.Rows.Add(tr);
DataTable dtdcDetails = new DataTable();
objRetailPL.sno = Convert.ToInt32(dtdate.Rows[i]["sno"].ToString());
dtdcDetails = objRetailBAL.dtdateTallyTable(objRetailPL);
GridView gv = new GridView();
//gv.ID = "gv" + dtdate.Rows[i]["BranchDate"].ToString();
gv.Width = 600;
Label lblTotal = new Label();
Label lbltotaleggs = new Label();
BoundField partyname = new BoundField();
partyname.HeaderText = "PartyName";
partyname.DataField = "partyname";
gv.Columns.Add(partyname);
BoundField birdtype = new BoundField();
birdtype.HeaderText = "Bird Type";
birdtype.DataField = "birdname";
gv.Columns.Add(birdtype);
BoundField totweight = new BoundField();
totweight.HeaderText = "Total Weight";
totweight.DataField = "totalweight";
gv.Columns.Add(totweight);
BoundField rateperkg = new BoundField();
rateperkg.HeaderText = "Rate/Kg";
rateperkg.DataField = "rateperkg";
gv.Columns.Add(rateperkg);
BoundField Bdcno = new BoundField();
Bdcno.HeaderText = "DCNo";
Bdcno.DataField = "dcno";
gv.Columns.Add(Bdcno);
// Here I want to add Button(confirm) In dynamic Gridview..
gv.AutoGenerateColumns = false;
gv.ShowFooter = true;
gv.DataSource = dtdcDetails;
gv.DataBind();
}
}
}
how can i add button control in Dynamic gridview , i tried with Templeate field, but i am not getting exactly output...after how can i add Button Click event for it? please help me?
Thanks in advance...
Sambasiva
You cannot add control dynamically in GridView Control,
You need to create a class and extends it ITemplate.
Following links will explain it
http://www.codedigest.com/Articles/ASPNET/168_Create_Dynamic_GridView_Control_in_C_ASPNet.aspx
http://www.codeproject.com/Articles/13462/How-to-create-template-columns-dynamically-in-a-gr

Need to Retrieve data from dynamically added text boxes

I added text boxes dynamically in ASP.Net from server side. By using one example which is shown in followed link
http://www.dotnettips4u.com/2013/03/dynamically-creating-text-boxes-using-c.html.
But I couldn't find out how to retrieve values from those text boxes..
Please help me to come out from this..
Here I am posting my code also..
Client Side Code:
<asp:TextBox ID="NoOfPsngr" runat="server" />
<asp:Button ID="AddP" runat="server" Text="Add Passengers" OnClick="AddP_Click" />
<asp:Panel runat="server" ID="passengerdet">
</asp:Panel>
Server Side Code:
protected void AddP_Click(object sender, EventArgs e)
{
int rowCount = Convert.ToInt32(NoOfPsngr.Text);
Table table = new Table();
table.ID = "PsngrTbl";
//Create the textboxes and labels each time the button is clicked.
for (int i = 0; i < rowCount; i++)
{
TableRow row = new TableRow();
TableCell namelblCell = new TableCell();
Label namelbl = new Label();
namelbl.Text = "Name";
TableCell nameTxtCell = new TableCell();
TextBox nameTxt = new TextBox();
TableCell typelblCell = new TableCell();
Label typelbl = new Label();
typelbl.Text = "Type";
TableCell typeSelectCell = new TableCell();
DropDownList typeSelect = new DropDownList();
ListItem adultItem = new ListItem();
adultItem.Text = "Adult";
adultItem.Value = "Adult";
typeSelect.Items.Add(adultItem);
ListItem childItem = new ListItem();
childItem.Text = "Child";
childItem.Value = "Child";
typeSelect.Items.Add(childItem);
ListItem infantItem = new ListItem();
infantItem.Text = "Infant";
infantItem.Value = "Infant";
typeSelect.Items.Add(infantItem);
TableCell etktlblCell = new TableCell();
Label etktlbl = new Label();
etktlbl.Text = "Eticket No";
TableCell etktTxtCell = new TableCell();
TextBox etktTxt = new TextBox();
//Adding.....
namelblCell.Controls.Add(namelbl);
typelblCell.Controls.Add(typelbl);
etktlblCell.Controls.Add(etktlbl);
nameTxtCell.Controls.Add(nameTxt);
typeSelectCell.Controls.Add(typeSelect);
etktTxtCell.Controls.Add(etktTxt);
nameTxt.ID = "PName" + i;
typeSelect.ID = "PType" + i;
etktTxt.ID = "ETkt" + i;
row.Controls.Add(namelblCell);
row.Controls.Add(nameTxtCell);
row.Controls.Add(typelblCell);
row.Controls.Add(typeSelectCell);
row.Controls.Add(etktlblCell);
row.Controls.Add(etktTxtCell);
table.Rows.Add(row);
}
passengerdet.Controls.Add(table);
}
use javascript like
$('#PsngrTbl').find('input[type=radio]').each(function (index, element) {
var o = $(this);
var oID = o.attr("id");
var oValue;
var controlName = $(this).attr('name');
if ($('[name=' + controlName + ']:checked').val() == undefined) {
oValue = "";
}
else {
oValue = $('[name=' + controlName + ']:checked').val();
}
});
$('#PsngrTbl').find('input[type=checkbox]').each(function (index, element) {
var o = $(this);
var value;
if (o.on == true) {
value = 1;
}
else {
value = 0;
}
var oID = o.attr("id");
var oValue = value;
});
$('#PsngrTbl').find('textarea').each(function (index, element) {
var o = $(this);
var oID = o.attr("id");
var oValue = o.val();
});
$('#PsngrTbl').find('select').each(function (index, element) {
var o = $(this);
var oID = o.attr("id");
var oValue = o.val();
});
It will return all values of controlls of that table

Update one cell after adding the new row with same values in gridview

I want to make shopping cart Datatable, I wrote the following code here to make the list of products
public DataTable ShoppingCartlist(string proname , string country,
string area ,string address,int quantity,decimal price,DateTime date)
{
DataTable dt = new DataTable();
if (HttpContext.Current.Session["ShoppingList"]==null)
{
dt.Columns.Add("ProName");
dt.Columns.Add("odate");
dt.Columns.Add("ocountry");
dt.Columns.Add("oarea");
dt.Columns.Add("oaddress");
dt.Columns.Add("quantity");
dt.Columns.Add("price");
dt.Columns.Add("SubTotal");
dt.Constraints.Add("Proid_PK", dt.Columns[0], true);
}
else
{
dt = (DataTable)HttpContext.Current.Session["ShoppingList"];
DataRow dr = dt.NewRow();
dr[0] = proname;
dr[1] = date;
dr[2] = country;
dr[3] = area;
dr[4] = address;
dr[5] = quantity;
dr[6] = price;
dr[7] = quantity * price;
dt.Rows.Add(dr);
}
return dt;
}
It binds the data fine with no problem, but where I insert the same row with same value it inserted in new record in the gridview, I don't want it like that I want update just one cell (I mean when I add new record with same values I want Quantity value on increase without adding new record in gridview) like I mark on the image
after long testing and googleing i finally get it done , here the code i used
public DataTable ShoppingCartlist(string proname , string country,
string area ,string address,int quantity,decimal price,DateTime date)
{
DataTable dt = new DataTable();
if (HttpContext.Current.Session["ShoppingList"]==null)
{
dt.Columns.Add("ProName");
dt.Columns.Add("odate");
dt.Columns.Add("ocountry");
dt.Columns.Add("oarea");
dt.Columns.Add("oaddress");
dt.Columns.Add("quantity");
dt.Columns.Add("price");
dt.Columns.Add("SubTotal");
DataRow dr = dt.NewRow();
dr[0] = proname;
dr[1] = date;
dr[2] = country;
dr[3] = area;
dr[4] = address;
dr[5] = quantity;
dr[6] = price;
dr[7] = quantity * price;
dt.Rows.Add(dr);
}
else
{
dt = (DataTable)HttpContext.Current.Session["ShoppingList"];
DataView dv = dt.DefaultView;
dv.Sort = "ProName";
int found;
string Proname;
DataRow dr;
for (int i = 0; i < dt.Rows.Count; i++)
{
dr = dt.Rows[i];
Proname = dr[0].ToString();
found = dv.Find(Proname);
if (found != -1)
{
foreach (DataRow pro in dt.Rows)
{
for (int x = 0; x < dt.Rows.Count; x++)
{
if (dt.Rows[x]["ProName"].ToString()==Proname)
{
dt.Rows[x]["quantity"] = Convert.ToInt16(dt.Rows[x]["quantity"]) + quantity;
}
}
}
}
}
}
return dt;
}
You could use LINQ:
DataTable dt = new DataTable("products");
dt.Columns.Add("ProName", typeof(string));
dt.Columns.Add("odate", typeof(DateTime));
dt.Columns.Add("ocountry", typeof(string));
dt.Columns.Add("oarea", typeof(string));
dt.Columns.Add("oaddress", typeof(string));
dt.Columns.Add("quantity", typeof(int));
dt.Columns.Add("price", typeof(decimal));
dt.Columns.Add("SubTotal", typeof(decimal));
DataRow dr1 = dt.NewRow();
dr1[0] = "test";
dr1[1] = new DateTime(2005, 5, 15);
dr1[2] = "US";
dr1[3] = "test area";
dr1[4] = "555";
dr1[5] = 1;
dr1[6] = 5.25;
dr1[7] = 5.25 * 1;
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2[0] = "test";
dr2[1] = new DateTime(2005, 5, 15);
dr2[2] = "US";
dr2[3] = "test area";
dr2[4] = "555";
dr2[5] = 3;
dr2[6] = 5.25;
dr2[7] = 5.25 * 3;
dt.Rows.Add(dr2);
var shoppingCart = from r in dt.AsEnumerable()
group r by new
{
ProName = r.Field<string>("ProName"),
odate = r.Field<DateTime>("odate"),
ocountry = r.Field<string>("ocountry"),
oarea = r.Field<string>("oarea"),
oaddress = r.Field<string>("oaddress"),
price = r.Field<decimal>("price")
} into g
select new
{
g.Key.ProName,
g.Key.odate,
g.Key.ocountry,
g.Key.oarea,
g.Key.oaddress,
g.Key.price,
quantity = g.Sum(s1 => s1.Field<int>("quantity")),
SubTotal = g.Sum(s2 => s2.Field<decimal>("SubTotal"))
};
foreach (var p in shoppingCart)
{
Console.WriteLine("Product: {0}, Quantity: {1}, Subtotal: {2}", p.ProName, p.quantity, p.SubTotal);
}
Results:
Product: test, Quantity: 4, Subtotal: 21.00

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