I want the checkbox control to be added dynamically with different id's in different th tags generating in a loop
<table border="1">
<thead>
<%string j = " Check"; %>
<%for (int i = 0; i < 10;i++ )
{%>
<th style="padding:2px; width:500px;">Table Head<br /><br />
<%
CheckBox chk = new CheckBox();
chk.ID = i + j;
chk.Text = "I am " + i + j;
%>
//I want this checkbox to be added dynamically here with different id's in different th tags generating in a loop
<asp:CheckBox runat="server" ID="<%=i+j%>"/>
</th>
<%} %>
</thead>
</table>
the way to do this is to create yourself a server-control with all the parameters you need, creating the controls in the OnInit, and rendering html in the RenderControl, and accessing the controls from public props like this:
public class DynamicCbs : Control
{
public int CtrlsCount { get; set; }
public List<CheckBox> lstCheckBoxs;
/// decleration of controls must be in the OnInit since the next stage of the page life cycle is to connect whatever came back from the client to the server
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
lstCheckBoxs = new List<CheckBox>();
for (int i = 0; i < CtrlsCount; i++)
{
string id = "DynamicCbs" + i;
CheckBox cbx = new CheckBox()
{
ID = id,
Text = "i am " + id
};
lstCheckBoxs.Add(cbx);
//add controls to control tree
this.Controls.Add(cbx);
}
}
/// here you must build ur html
public override void RenderControl(HtmlTextWriter writer)
{
writer.RenderBeginTag(HtmlTextWriterTag.Table);
writer.RenderBeginTag(HtmlTextWriterTag.Thead);
foreach (var cbx in lstCheckBoxs)
{
writer.RenderBeginTag(HtmlTextWriterTag.Th);
cbx.RenderControl(writer);
writer.RenderEndTag();
}
writer.RenderEndTag();//thead
writer.RenderEndTag();//table
}
}
full example
ok I found the solution. I have use asp:Table control to solve this problem
My aspx page code is :
<asp:Table ID="ObjectwiseTable2" runat="server"
CssClass="AccessTable" BorderColor="Black" width="100%">
</asp:Table>
My .cs page code to Add content and dynamic content in the table is :
TableHeaderRow thead = new TableHeaderRow();
TableHeaderCell th = new TableHeaderCell();
th.Controls.Add(new LiteralControl("Object Wise Detail(s)"));
th.RowSpan = 2;
thead.Cells.Add(th);
int totalUsers = accesswiseDt.Rows.Count;
for (int User = 0; User < totalUsers; User++)
{
TableHeaderCell th2 = new TableHeaderCell();
th2.Controls.Add(new LiteralControl(accesswiseDt.Rows[User]["users"].ToString()));
IsReviewPending = view_access.IsWaitingForViewAccess(ApplicationTree.SelectedNode.Value, Session["empCode"].ToString(), accesswiseDt.Rows[User]["empcode"].ToString());
if (IsReviewPending)
{
th2.Controls.Add(new LiteralControl("<br />"));
CanReviewAccess = true;
//Code for Adding Dynamic control in specific cell of the table
CheckBox chk = new CheckBox();
chk.ID = ApplicationTree.SelectedNode.Value + "_" + accesswiseDt.Rows[User]["empcode"].ToString();
chk.Text = "Access Reviewed";
th2.Controls.Add(chk);
}
thead.Cells.Add(th2);
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ResetEmpNominee();
}
if (Convert.ToInt32(ddlEmployee.SelectedValue) > 0)
{
populateTrainingInfo(Convert.ToInt16(ddlEmployee.SelectedValue));
}
}
protected void btnTrainingSave_Click(object sender, EventArgs e)
{
try
{
short empID = 0;
if (empID =0)
{
success = hrServer.addToEmpTraining(trainingNew, path);
if (success.Equals("Success"))
{
Msg = "Successfully Added..."; }
else
{
Msg = success;
}
}
else
{
}
WebUtil.jsCall("alert('" + Msg + "')", this);
Page_Load(null, null);
}
catch (Exception ex)
{
WebUtil.MessageBox_Show(ex.Message, this);
}
}
private void populateTrainingInfo(short empID)
{
HumanResourceServer hrServer = new HumanResourceServer();
DataSet trainingInfoes = hrServer.GetEmployeeTrainingInfo(empID);
int i = 0;
int count = trainingInfoes.Tables[0].Rows.Count;
ViewState["TrainingInfo"] = trainingInfoes.Tables[0];
int k = 0;
DataTable dtTraining = trainingInfoes.Tables[0];
for (i = 0; i < dtTraining.Rows.Count; i++)
{
//first row
Table tblTraining = new Table();
tblTraining.Width = 900;
TableCell tcLeft1 = new TableCell();
TableCell tcRight1 = new TableCell();
TableRow tr1 = new TableRow();
tr1.CssClass = "cvItemSubHeader";
Label lblHeader1 = new Label();
lblHeader1.ID = "Training" + Convert.ToString(i + 1);
lblHeader1.Text = "Training :" + Convert.ToString(i + 1);
tcLeft1.CssClass = "cvColumnCaption";
//tcLeft1.CssClass = "cvItemButtonCell";
tcLeft1.Controls.Add(lblHeader1);
tcLeft1.HorizontalAlign = HorizontalAlign.Left;
Button btnTrainingEdit = new Button();
btnTrainingEdit.ID = "btnTrainingEdit" + Convert.ToString(i + 1);
btnTrainingEdit.Text = "Edit";
btnTrainingEdit.CssClass = "DSEButton4";
//Label lblHeader2 = new Label();
//lblHeader2.ID = "LevelofEducationData" + Convert.ToString(i);
//lblHeader2.Text = dtTraining.Rows[i]["EDUCATIONLEVELNAME"].ToString();
tcRight1.HorizontalAlign = HorizontalAlign.Right;
//tcRight1.Style["Padding-left"] ="50";
tcRight1.CssClass = "cvItemButtonCell";
tcRight1.Controls.Add(btnTrainingEdit);
tr1.Cells.Add(tcLeft1);
tr1.Cells.Add(tcRight1);
tblTraining.Rows.Add(tr1);
btnTrainingEdit.Click += new System.EventHandler(btnTrainingEdit_click);
tcRight1.Controls.Add(btnTrainingEdit);
tr1.Cells.Add(tcLeft1);
tr1.Cells.Add(tcRight1);
tblTraining.Rows.Add(tr1);
//hidden row for educationid
tcLeft1 = new TableCell();
tcRight1 = new TableCell();
tr1 = new TableRow();
tr1.CssClass = "hiddenDynamicRows";
lblHeader1 = new Label();
lblHeader1.ID = "TRAININGID" + Convert.ToString(i + 1);
lblHeader1.Text = "TRAININGID";
tcLeft1.CssClass = "cvColumnCaption";
tcLeft1.Controls.Add(lblHeader1);
tcLeft1.HorizontalAlign = HorizontalAlign.Left;
Label lblHeader2 = new Label();
lblHeader2.ID = "TRAININGIDData" + Convert.ToString(i + 1);
lblHeader2.Text = dtTraining.Rows[i]["TRAININGID"].ToString();
tcRight1.Controls.Add(lblHeader2);
tr1.Cells.Add(tcLeft1);
tr1.Cells.Add(tcRight1);
tblTraining.Rows.Add(tr1);
Trainings.Controls.Add(tblTraining);
}
count = trainingInfoes.Tables[0].Rows.Count;
}
aspx page contain some following code
<table class="contentRow" width="900px">
<tr class="cvItemHeader" align="left">
<td align="left" >
<div><div class="cvItemHeaderText"> Training Summary </div>
<div class="cvItemHeaderButton">
<asp:Button ID="btnAddTraining" runat="server" CssClass="DSEButton4"
Text="Add" onclick="btnAddTrainingInfo_Click" /> </div>
</div>
</td>
</tr>
<div id="Trainings" runat="server"></div>
</table>
Sorry, for my unclear question. btnTrainingSave_Click method save data into database. I need to update the div with id='Trainings' after saving the data into database. I called page_load method at the end of btnTrainingSave_Click method. But it does not work. can anybody help me how can I do that? Perhaps this time my question is clear.
the concept is wrong, to refresh the page redirect to the same URL
Page.Response.Redirect(Page.Request.Url.ToString(), true);
i have an asp.net website that will deployed to a server.
on one of the page, i have a page that load crystal report viewer on pageLoad()
and i want when the user click on a button there, it will print the report to their printer.
this is my asp page that contains the crystal report viewer and the button:
<body>
<link href="style.css" rel="stylesheet" type="text/css" />
<form id="form1" runat="server">
<table align="center">
<tr>
<td align=left>
<asp:LinkButton ID="toHome_LinkButton1" runat="server" onclick="toHome_LinkButton1_Click"><<< Home</asp:LinkButton>
</td>
<td align=right>
<asp:Button ID="print" runat="server" Text="Print" CssClass="css_button" OnClick="print_Click" />
</td>
</tr>
<tr>
<td colspan=2 align=center>
<CR:CrystalReportViewer ID="crv1" runat="server"
EnableDatabaseLogonPrompt="False" EnableParameterPrompt="False"
ToolPanelView="None" GroupTreeStyle-ShowLines="False" HasCrystalLogo="False"
HasDrilldownTabs="False" HasDrillUpButton="False" HasExportButton="False"
HasGotoPageButton="False" HasPageNavigationButtons="False"
HasPrintButton="False" HasSearchButton="False" HasToggleGroupTreeButton="False"
HasToggleParameterPanelButton="False" HasZoomFactorList="False"
PrintMode="ActiveX" />
</td>
</tr>
</table>
</form>
i've already try using PrinToPrinter() method, but as far as i know those method only for server side printing, because we have to declare the printer's name, am i right ?
and this is my button onClick:
(note that i still use PrintToPrinter method that i think is server side printing)
protected void print_Click(object sender, EventArgs e)
{
string url = Request.ServerVariables["QUERY_STRING"];
string[] kodeKwitansi = url.Split('=');
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
SqlCommand select = con.CreateCommand();
select.CommandText = "SELECT k.no_kwitansi, k.kode_vendor, k.nama_vendor, u.nama_pekerja, k.nama_pekerja_penanggungjawab, k.satuan, k.jumlah, k.jenis_pembayaran, k.tanggal FROM tb_kwitansi k, tb_user u WHERE k.no_kwitansi = '" + kodeKwitansi[1] + "' AND (k.nomor_pekerja = u.nomor_pekerja)";
con.Open();
SqlDataReader reader = select.ExecuteReader();
reader.Read();
noKwitansi = reader["no_kwitansi"].ToString();
kode_vendor = reader["kode_vendor"].ToString();
namaVendor = reader["nama_vendor"].ToString();
namaPekerja = reader["nama_pekerja"].ToString();
namaPJ = reader["nama_pekerja_penanggungjawab"].ToString();
satuan = reader["satuan"].ToString();
nominal = reader["jumlah"].ToString();
jenisPembayaran = reader["jenis_pembayaran"].ToString();
con.Close();
rd.Load(MapPath("Kwitansi.rpt"));
TextObject to = (TextObject)rd.ReportDefinition.ReportObjects["Text7"];
to.Text = noKwitansi;
to = (TextObject)rd.ReportDefinition.ReportObjects["Text10"];
to.Text = kode_vendor;
to = (TextObject)rd.ReportDefinition.ReportObjects["Text11"];
string[] val = nominal.Split('.');
string val2 = "";
int n = val[0].Length;
int count = 0;
int tan = 0;
for (int i = n - 1; i >= 0; i--)
{
if (val[0][i] == '.')
{
val2 = val[0][i] + val2;
tan = 1;
}
else if (val[0][i] >= '0' && val[0][i] <= '9')
{
val2 = val[0][i] + val2;
count++;
if (count == 3 && i != 0 && tan == 0)
{
val2 = "," + val2;
count = 0;
}
}
}
if (val.Count() == 2)
{
val2 = val2 + "." + val[1];
}
to.Text = val2;
to = (TextObject)rd.ReportDefinition.ReportObjects["Text12"];
if (satuan.Equals("$"))
{
to.Text = terbilang(nominal);
}
else
{
to.Text = terbilang(nominal);
}
to = (TextObject)rd.ReportDefinition.ReportObjects["Text13"];
to.Text = jenisPembayaran;
to = (TextObject)rd.ReportDefinition.ReportObjects["Text15"];
to.Text = namaPJ;
to = (TextObject)rd.ReportDefinition.ReportObjects["Text8"];
to.Text = namaVendor;
rd.PrintOptions.PrinterName = "Canon Inkjet iP3600 series";
rd.PrintToPrinter(1, true, 0, 0);
rd.Close();
rd.Dispose();
Response.Redirect("LihatKwitansi.aspx?"+url);
}
and i read that we can use javascript's windows.Print(), but again as far as i know when we use window.Print() it will print the whole page, while i want only the report to be printed.
so can anyone help me to do this ?
what i need is when the user access my page from their computer, then they click on the button, it will print the report directly to printer that connected to their computer.
any help would be appreciated
thanks in advance :)
The Crystal Report viewer control has this feature built in, but you have disabled it, with this option:
HasPrintButton="False"
Is there a particular reason you don't want to use the built in feature? If not, then simply set this option to True.
What you have to do to print to the client's printer is to give access to the crystal client side printing api by setting PrintMode="ActiveX" in the report viewer control, or use a hidden PDF.
Since I wanted to simplify what the users had to install on each client I went with the hidden pdf option and a separate button to print to client.
On the aspx page I have an asp literal that I populate with the pdf embeded object at 1px x 1px so it isn't visible to the user. Then on pageload call the printToPrinter method.
// On server side
// Export to PDF
Guid imageGuid = Guid.NewGuid();
string _pdfName = String.Format(#"{0}{1}{2}.pdf", _pdfPath, _reportName, imageGuid);
// expport to unique filename
// ...
// Display the pdf object
_sb.AppendFormat("<object ID=\"pdfObject\" type=\"application/pdf\" data=\"{0}\" src=\"{0}\" style=\"width: {1}; height: {2}; ", _pdf2Name, _width, _height);
_sb.AppendLine("z-index:1; display: block; border: 1px solid #cccccc; top: 0; left: 0; position: absolute;-+ \">");
_sb.Append("</object>");
pdfLiteral.Text = _sb.ToString();
pdfLiteral.Visible = true;
// javascript
// on document read call the printWithDialog function
var code = function(){
try
{
var pdf = $get('pdfObject');
if (pdf == null)
return;
try {
pdf.printWithDialog();
}
catch (err) {
alert('Please Install Adobe Acrobat reader to use this feature');
}
}
catch(err)
{
}
};
window.setTimeout(code, 1000);
I am trying to add a check box, label and DDL to ASP.NET page (aspx) from my back class in C#. I have been using LiteralControl _liText = new LiteralControl(); to attach label so that I can show them using this.Controls.Add(_liText);in CreateChildControls() method.
How do I add DDL and check box to ASp.NET page from C# code so that my label is in the same line with DDL and checkbox?
I have already made DDL using this syntax:
List<DropDownList> _ddlCollection=new List<DropDownList>();
for (int i = 0; i < 5; i++)
{
_ddlCollection.Add(new DropDownList());
}
Problem is not in this.Controls.Add() which I call from CreateChildControls(). It is OnPreRender() method where I fill ddl and check box. Is LiteralControl class good for this? Here is what I have tried in OnPReRender():
foreach (SPList list in web.Lists)
{
if (!list.Hidden)
{
_liText.Text += #<input type="checkbox">;
_liText.Text += list.Title + "<br />";
}
}
Your controls exist but the page or user control are not aware of them.
You need to add your control to the page
Page.Controls.Add(_ddlCollection);
You can also add your controls to other controls on the page, for example a panel.
panel1.Controls.Add(_ddlCollection);
You are adding a list of dropdowns which I don't think is what you want.
You need to add ListItems instead.
var dropDown = new DropDownList {Id = "dropDown1"};
dropDown.Items.Add(new ListItem("text", "value");
Page.Controls.Add(dropDown);
Add a label for the dropdown.
Page.Controls.Add(new Label {AssociatedControlId = dropDown.Id, Text = "Drop me down"});
For your other controls follow the same process:
Add a checkbox
Don't add an html control to a literal unless that is really what you want.
If you want to be able to access that checkbox in the code behind then you need to add it as an asp.net control. User a placeholder.
placeHolder1.Controls.Add(new CheckBox {Id = "chkBox", Text="Tick me"});
The text property on the checkbox will be the label for the check box and tick/untick the check box when you click on the text.
Output should be
<label for="dropDown1" >Drop me down</label>
<select id="dropDown1" >
<option value="value" >text</option>
</select>
<input type="checkbox" id="chkbox" />
<label for="chkbox" >Tick me</label>
First, you should add a placeholder.
<form id="form1" runat="server">
<asp:PlaceHolder runat="server" ID="phMain"></asp:PlaceHolder>
</form>
Next, if you have add in one line you use table (It is a simple but not recommended method, next step add all to Page and set css style for the page).
protected override void CreateChildControls()
{
base.CreateChildControls();
Table table = new Table();
for (int i = 0; i < 3; i++)
{
TableRow tr = new TableRow();
TableCell tc1 = new TableCell();
tc1.Controls.Add(new LiteralControl(String.Format("Line {0}",i)));
tr.Cells.Add(tc1);
TableCell tc2 = new TableCell();
CheckBox chb = new CheckBox();
chb.ID = String.Format("CheckBox_{0}", i);
chb.Text = String.Format("CheckBox {0}", i);
chb.CheckedChanged += chb_CheckedChanged;
chb.AutoPostBack = true;
tc2.Controls.Add(chb);
tr.Cells.Add(tc2);
TableCell tc3 = new TableCell();
DropDownList ddl = new DropDownList();
ddl.ID = String.Format("DropDownList_{0}", i);
ddl.Items.Add("1111");
ddl.Items.Add("2222");
ddl.Items.Add("3333");
ddl.SelectedIndex = i;
ddl.Enabled = false;
tc3.Controls.Add(ddl);
tr.Cells.Add(tc3);
table.Rows.Add(tr);
}
phMain.Controls.Add(table);
}
void chb_CheckedChanged(object sender, EventArgs e)
{
CheckBox chb = sender as CheckBox;
string ddlid = chb.ID.Replace("CheckBox", "DropDownList");
DropDownList ddl = this.Page.FindControl(ddlid) as DropDownList;
if (ddl != null)
{
ddl.Enabled = chb.Checked;
}
}
I have some settings stored in web.config like this:
<add key="Answers" value="radiobutton1,radiobutton2,radiobutton3"/>
Radiobutton1, radiobutton2 and radiobutton3 are radiobutton label values.
In settings.cs I have a function to retrieve value from web.config:
public static string Answers
{
get
{
return System.Configuration.ConfigurationManager.AppSettings["Answers"];
}
}
.ascx file:
<table runat="server" OnPreRender="Radio_PreRender" id="table1" name="table1">
</table>
My ascx.cs file contains this function:
protected void Radio_PreRender(object sender, EventArgs e)
{
if (Settings.Answers != "")
{
int counter = 0;
string a = Settings.Answers;
string[] words = a.Split(',');
StringWriter stringwriter = new StringWriter();
HtmlTextWriter writer = new HtmlTextWriter(stringwriter);
foreach (string word in words)
{
writer.WriteBeginTag("tr");
writer.WriteBeginTag("td");
writer.Write("abc123");
RadioButton rdb1 = new RadioButton();
rdb1.Checked = true;
rdb1.GroupName = "rdbgroup";
rdb1.ID = "radiobutton" + counter;
rdb1.Text = word;
table1.Controls.Add(rdb1 );
writer.WriteEndTag("td");
writer.WriteBeginTag("tr");
table1.Render(writer);
counter++;
}
}
}
In other words, I want to generate a dynamic number of this code inside table1:
<tr>
<td>
// input type="radiobutton" and label go here.
</td>
</tr>
At the moment radiobuttons are not generated, because they can't be direct child elements to a table. If I specify a div instead, radiobuttons are generated, but everything I try to write with HtmlTextWriter is not. I understand that my html has to be rendered by using table1.Render(writer); or something similar, but I can't figure it out.
You can try creating a table and add it to the page you are working on, using the exmaple below you can replace the textbox with a radiobutton
Here is an example:
//Creat the Table and Add it to the Page
Table table = new Table();
table.ID = "Table1";
Page.Form.Controls.Add(table);
// Now iterate through the table and add your controls
for (int i = 0; i < rowsCount; i++)
{
TableRow row = new TableRow();
for (int j = 0; j < colsCount; j++)
{
TableCell cell = new TableCell();
TextBox tb = new TextBox();
// Set a unique ID for each TextBox added
tb.ID = "TextBoxRow_" + i + "Col_" + j;
// Add the control to the TableCell
cell.Controls.Add(tb);
// Add the TableCell to the TableRow
row.Cells.Add(cell);
}
// Add the TableRow to the Table
table.Rows.Add(row);
}
I do this quite often by running the user control through its full asp.net lifetime and getting it as a string:
http://www.diaryofaninja.com/blog/2009/09/14/a-simple-solution-to-viewing-a-preview-of-any-page-in-your-site
This way you can use ASP.Net as a templating engine for anything
Page tempPage = new Page();
UserControl myUserControl = new MyUserControl();
tempPage.Controls.Add(myUserControl);
StringWriter sw = new StringWriter();
HttpContext.Current.Server.Execute(tempPage, sw, false);
if (!String.IsNullOrEmpty(sw.ToString()))
{
return sw.ToString();
}
I am trying to get some values from a List and then create a html table with this data but I can't get it to work properly.
I have:
HtmlTable table = new HtmlTable();
HtmlTableRow row;
HtmlTableCell cell;
foreach(var item in Name)
{
row = new HtmlTableRow();
foreach(var familyName in item.familyName)
{
cell = new HtmlTableCell();
cell.InnerText = item.familyName.ToString();
row.Cells.Add(cell);
}
foreach (var givenName in item.givenName)
{
cell = new HtmlTableCell();
cell.InnerText = item.givenName.ToString();
row.Cells.Add(cell);
}
table.Rows.Add(row);
}
this.Controls.Add(table);
When I step through the debugger I can see that row.Cells.Add(cell) contains the family name in the first loop and given name in the second loop but then something seems to be wrong and I can't get the table to show up on the page with this data.
When I check the table.rows.add(row) it says that
base {System.SystemException} = {"'HtmlTableRow' does not support the InnerText property."}
What am I doing wrong here?
I've stepped through your code and I can't replicate the error you mention.
It's difficult to say for sure without seeing your data structure Name but a couple of observations:
I. If familyName is a string, your inner foreach will execute once for each character in the string. This may not be what you want as it'll output a surname x number of times where x = surname.length.
This will result in unequal numbers of table cells per row unless all your surnames are the same length.
So I would say get rid of the
foreach(var familyName in item.familyName){...}
loop and just leave the code inside so it'll output surname just once.
II. I'm guessing that item.givenName is an array or collection e.g. List<> of strings? If so you could just use
cell.InnerText = givenName;
Note that this is will still give you uneven numbers of table cells per row because people have different numbers of forenames ;-)
Having said that you really ought to use the built in controls for doing this kind of thing - the Repeater is probably the way to go.
E.g.
Markup
<asp:Repeater runat="server" id="rptNames" onItemDataBound="rptName_ItemDataBound" >
<HeaderTemplate>
<table>
<tr>
<td>Given Name(s)</td>
<td>Family Name</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("FamilyName") %></td>
<td>
<asp:Label runat="server" id="lGivenNames" />
</td>
</tr>
<ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
CodeBehind
Probably triggered by Page_Load - just bind your repeater to your Name collection:
rptNames.DataSource = Name;
rptNames.DataBind();
To output the GivenNames you use the ItemDataBound event which gets called for each row of the repeater:
protected void rptNames_ItemDataBound(object sender, RepeaterItemEventArgs e){
//Not interested the Header and Footer rows
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem){
Label l = ((Label)e.Item.FindControl("lGivenNames"));
string[] arrGivenNames = ((FullName)e.Item.DataItem).GivenNames;
foreach (string n in arrGivenNames){//could use a StringBuilder for a performance boost.
l.Text += n + " "; //Use a regular space if using it for Winforms
}
//For even slicker code, replace the Label in your repeater with another repeater and bind to that. Google `nested repeater` for a how to.
}
}
HTH.
Full Code
<h2>Doing it by hand - manually building up an HTML Table</h2>
<asp:Panel runat="server" ID="pnl1">
</asp:Panel>
<h2>With a Repeater</h2>
<asp:Repeater runat="server" id="rptNames" onItemDataBound="rptName_ItemDataBound" >
<HeaderTemplate>
<table border="1" style="border-color:Red;">
<tr>
<td>Given Name(s)</td>
<td>Family Name</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("FamilyName") %></td>
<td>
<asp:Label runat="server" id="lGivenNames" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace Testbed.WebControls
{
internal class FullName{
public string FamilyName{get;set;}
public string[] GivenNames{get;set;}
public FullName(){
}
public FullName(string[] _givenNames, string _familyName)
{
FamilyName = _familyName;
GivenNames = _givenNames;
}
}
public partial class HTMLTables : System.Web.UI.Page
{
List<FullName> Name;
protected void Page_Load(object sender, EventArgs e)
{
this.Name = new List<FullName>();
Name.Add(new FullName(new string[]{"Kylie"},"Minogue"));
Name.Add(new FullName(new string[]{"Angelina", "Kate", "Very-Lovely"}, "Jolie"));
Name.Add(new FullName(new string[]{"Audrey", "Veronica"},"Hepburn"));
HtmlTable table = new HtmlTable();
table.Border = 1;
HtmlTableRow row;
HtmlTableCell cell;
row = new HtmlTableRow();
cell = new HtmlTableCell();
cell.InnerText = "Given Name";
row.Cells.Add(cell);
cell = new HtmlTableCell();
cell.InnerText = "Family Name";
row.Cells.Add(cell);
foreach (var item in Name)
{
row = new HtmlTableRow();
//foreach (var familyName in item.FamilyName){
cell = new HtmlTableCell();
cell.InnerText = item.FamilyName.ToString();
row.Cells.Add(cell);
//}
foreach (string givenName in item.GivenNames)
{
cell = new HtmlTableCell();
cell.InnerText = givenName.ToString();
row.Cells.Add(cell);
}
table.Rows.Add(row);
}
this.pnl1.Controls.Add(table);
//Or do it with a repeater
rptNames.DataSource = Name;
rptNames.DataBind();
}
//This gets called everytime a data object gets bound to a repeater row
protected void rptName_ItemDataBound(object sender, RepeaterItemEventArgs e){
switch(e.Item.ItemType){
case ListItemType.Item:
case ListItemType.AlternatingItem:
string[] arrGivenNames = ((FullName)e.Item.DataItem).GivenNames;
foreach(string n in arrGivenNames){
((Label)e.Item.FindControl("lGivenNames")).Text += n + #" ";
}
break;
default:
break;
}
}
}
}