How to create line breaks between dynamically generated labels in a placeholder? - asp.net

This is the code below in code behind file's Page_Load event:
LinkButton linkButton = new LinkButton();
linkButton.ID = "LinkButtonDynamicInPlaceHolder1Id" + i;
linkButton.ForeColor = Color.Blue;
linkButton.Font.Bold = true;
linkButton.Font.Size = 14;
linkButton.Font.Underline = false;
linkButton.Text = itemList[i].ItemTitle.InnerText;
linkButton.Click += new EventHandler(LinkButton_Click);
linkButton.Attributes.Add("LinkUrl",itemList[i].ItemLink.InnerText);
PlaceHolder1.Controls.Add(linkButton);
Label label = new Label();
label.ID = "LabelDynamicInPlaceHolder1Id" + i;
label.ForeColor = Color.DarkGray;
label.Text = itemList[i].ItemDescription.InnerText;
PlaceHolder1.Controls.Add(label);
I want a line break between each control generated.

Solution to your Line Break issue is below however, if you're doing this in the Page_Load event, then your event handlers won't work and your going to run into Page Life Cycle issues. Basically, in order for your event handlers to fire on PostBack, you really need to be creating these dynamic controls earlier in the Page Life Cycle. Try moving your code to the OnInit method if you do run into this problem.
LinkButton linkButton = new LinkButton();
linkButton.ID = "LinkButtonDynamicInPlaceHolder1Id" + i;
linkButton.ForeColor = Color.Blue;
linkButton.Font.Bold = true;
linkButton.Font.Size = 14;
linkButton.Font.Underline = false;
linkButton.Text = itemList[i].ItemTitle.InnerText;
linkButton.Click += new EventHandler(LinkButton_Click);
linkButton.Attributes.Add("LinkUrl",itemList[i].ItemLink.InnerText);
PlaceHolder1.Controls.Add(linkButton);
//Add This
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
Label label = new Label();
label.ID = "LabelDynamicInPlaceHolder1Id" + i;
label.ForeColor = Color.DarkGray;
label.Text = itemList[i].ItemDescription.InnerText;
PlaceHolder1.Controls.Add(label);

Another solution is that you could add each control to a Panel, which will render them each in a <div> resulting in the effect you're looking for.
To me this would be more dynamic because if you hide any of the controls the div will collapse and not leave empty lines.
LinkButton linkButton = new LinkButton();
linkButton.ID = "LinkButtonDynamicInPlaceHolder1Id" + i;
linkButton.ForeColor = Color.Blue;
linkButton.Font.Bold = true;
linkButton.Font.Size = 14;
linkButton.Font.Underline = false;
linkButton.Text = itemList[i].ItemTitle.InnerText;
linkButton.Click += new EventHandler(LinkButton_Click);
linkButton.Attributes.Add("LinkUrl",itemList[i].ItemLink.InnerText);
//Add control to a panel, add panel to placeholder
Panel lbPan = new Panel();
lbPan.Controls.Add(linkButton);
PlaceHolder1.Controls.Add(lbPan);
Label label = new Label();
label.ID = "LabelDynamicInPlaceHolder1Id" + i;
label.ForeColor = Color.DarkGray;
label.Text = itemList[i].ItemDescription.InnerText;
//Add control to a panel, add panel to placeholder
Panel lblPan = new Panel();
lblPan.Controls.Add(label);
PlaceHolder1.Controls.Add(lblPan);

How to: Add Controls to an ASP.NET Web Page Programmatically
In some instances, you might want to
create both static text and controls.
To create static text, you can use either a Literal or a Label Web server
control. You can then add these
controls to the container as you would
any other control. For information
about view state in controls created
at run time, see Dynamic Web Server
Controls and View State.

Related

How to add rows and columns to a table in asp.net dynamically in button

I intend to create a dynamic table with the proviso that every time I click on the button I can add a row to that table.
I'm using the following code but it does not work.
For the first time I click on the button runs, but for the second time that must be added the second row it does not do so, and only one row is added to the previous.
In page
DropDownList[] dlsathetasilat = new DropDownList[50];
Label[] lblradif = new Label[50];
TextBox[] txtreshtetahsili = new TextBox[50];
TextBox[] txtmoasese = new TextBox[50];
TextBox[] txtcity = new TextBox[50];
TextBox []txtdateakhz = new TextBox[50];
CheckBox[] chmadrakmoadel = new CheckBox[50];
TableCell []tc = new TableCell[7];
static int i=0;
In button :
TableRow tr = new TableRow();
lblradif[i] = new Label();
lblradif[i].Text = (i + 1).ToString();
lblradif[i].CssClass = "lbl";
dlsathetasilat[i] = new DropDownList();
dlsathetasilat[i].Items.Add("دیپلم");
dlsathetasilat[i].CssClass = "dl";
txtreshtetahsili[i] = new TextBox();
txtreshtetahsili[i].CssClass = "dl";
txtmoasese[i] = new TextBox();
txtmoasese[i].CssClass = "dl";
txtdateakhz[i] = new TextBox();
txtdateakhz[i].CssClass = "dl";
txtcity[i] = new TextBox();
txtcity[i].CssClass = "dl";
chmadrakmoadel[i] = new CheckBox();
chmadrakmoadel[i].CssClass = "d2";
for (int k = 0; k < 7; k++)
tc[k] = new TableCell();
tc[0].Controls.Add(lblradif[i]);
tc[1].Controls.Add(dlsathetasilat[i]);
tc[2].Controls.Add(txtreshtetahsili[i]);
tc[3].Controls.Add(txtmoasese[i]);
tc[4].Controls.Add(txtcity[i]);
tc[5].Controls.Add(txtdateakhz[i]);
tc[6].Controls.Add(chmadrakmoadel[i]);
for (int j = 0; j < 7; j++)
tr.Controls.Add(tc[j]);
Table1.Rows.Add(tr);
i++;
This is the issue of PostBack and ViewState. ASP.NET does not save the ViewState for Table control. Which means if you want to keep the table data during the post back, you need to bind the table on every post back.
What you can do is save the table values in a ViewState object. Then write a function which creates the table by using the ViewState object. In the on click event of the button, add additional rows to the view state object and then call the function again to recreate the table. This looks quite simple, but the main problem is that if you have additional controls in the table, like TextBox, DropDownList etc. then they do not retain the values after postback, becuase we are recreating the table every time.
By looking at all these problems, I would consider using DataBound controls like Repeater with which you can build the table based on the number of rows that you want to create. Also you can deal with the dynamic controls if you want.

Find Dynamic columns of a RadGrid

I created Dynamic columns (textBox) in RadGrid on a Click Event. How do I find those Controls on another Click Event.
for (int i = 0; i < objISTUserDetailsObjectList.Count; i++)
{
tempCol = new GridTemplateColumn();
tempCol.ItemTemplate = new DynamicTemplateCoulmn("txtQuantity" + i, "numericTextBox");
tempCol.UniqueName = "Users" + i;
tempCol.HeaderStyle.HorizontalAlign = HorizontalAlign.Right;
tempCol.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
tempCol.FooterStyle.HorizontalAlign = HorizontalAlign.Right;
gvwISTProduct.MasterTableView.Columns.Add(tempCol);
}
I an unable to find the "txtxQuantity" on another Click event although i find it in Grids ItemDataBound event.
Thanks in Advance.

Loop through the labels of a page to assign text

I have some 20 labels on my aspx page for which the IDs are lbl1,lbl2....lbl20 and text is driven by SqlServer table. Is there any easy way to loop through all the labels on the page and assing the text from reader.
I did some thing like but it doesn't work.
SqlDataReader Reader = new SqlDataReader();
int i = 0;
while(Reader.read())
{
label lbl = new label();
lbl.ID = "label" + i;
lbl.text = Reader["ColumnName"].ToString();
}
Is there any other method through which I can loop through all the labels and assign text for it?
If you have them in a container, i think you can do something like this below:
For Each lbl As Control In Grid1.Children
If TypeOf lbl Is Label Then
'your logic
End If
Next
I have only tried this in silverlight however, so i'm not sure it works, or if putting them all in a container is practical in your case.
One way to do this is use the findcontrol method. This would work well because all your labels are named with a "lbl0", "lbl1"... convention.
**start looping:
int index = 0;
string currentLabel = "lbl" + index.ToString();
index++;
Control myControl1 = FindControl(currentLabel);
// cast control to type: (label)
// apply text from reader**
Give that a shot. Hope it works out
I have used this in the past and I just tested it out.
You can do this because every page has a form
HtmlForm form1 = (HtmlForm)Page.FindControl("ContentPlaceHolder1");
for (int i = 1; i <= 3; i++) {
((TextBox)form1.FindControl("label" + i)).Text = "This is label number " + i;
}
If you have a master page change the first line to this
ContentPlaceHolder ph = (ContentPlaceHolder)Page.FindControl("ContentPlaceHolder1");

ASP.NET AJAX Toolkit CalendarExtender not working C#

I have a folowing problem:
I have a page where I need to create a lot of elements dynamically from the code behind. It obviously depends on what is passed from the database, but the number of elements can change, that's why I cannot do it static.
What I have at the moment, is:
I have statically created PANEL:
<asp:Panel ID="pFullInfo_lStartDateStr" runat="server"></asp:Panel>
Then in Code Behind, I'm creating other Controls and add them to my Label. The Issue I have is that the CalendarExtender that should appear after clicking the iEditStartDateCalendar doesn't popup :( I can't see what I'm doing wrong here ? Any help please ?!?!
// StartDate
Label lStartDateSite = new Label();
pFullInfo_lStartDateStr.Controls.Add(lStartDateSite);
Label lStartDate = new Label();
pFullInfo_lStartDateStr.Controls.Add(lStartDate);
ImageButton ibEditStartDate = new ImageButton();
ibEditStartDate.ID = "ibEditStartDate_" + this_site_id;
pFullInfo_lStartDateStr.Controls.Add(ibEditStartDate);
TextBox tbEditStartDate = new TextBox();
pFullInfo_lStartDateStr.Controls.Add(tbEditStartDate);
Image iEditStartDateCalendar = new Image();
iEditStartDateCalendar.ID = "iEditStartDateCalendar";
iEditStartDateCalendar.ImageUrl = "~/i/small/calendar.png";
iEditStartDateCalendar.ImageAlign = ImageAlign.AbsMiddle;
pFullInfo_lStartDateStr.Controls.Add(iEditStartDateCalendar);
CalendarExtender ceEditStartDate = new CalendarExtender();
ceEditStartDate.ID = "ceEditStartDate_" + this_site_id;
ceEditStartDate.PopupButtonID = iEditStartDateCalendar.UniqueID;
ceEditStartDate.TargetControlID = tbEditStartDate.UniqueID;
ceEditStartDate.PopupPosition = CalendarPosition.Right;
pFullInfo_lStartDateStr.Controls.Add(ceEditStartDate);
Normally, when adding the calendar extender in markup, you'd just set the PopupButtonID and TargetControlID to the ID of those controls, not the UniqueID.
When adding things like Labels dynamically, you set the AssociatedControlID to the ID of the control, not the UniqueID/ClientID and the framework works it out at render time.
Also, most JavaScript libraries prefer you to use the actual id of the control, rather than the name attribute, so you should use ClientID instead.
I found the solution.
The problem was with the "UniqueID" I was passing.
The correct solution is here:
// StartDate
Label lStartDateSite = new Label();
pFullInfo_lStartDateStr.Controls.Add(lStartDateSite);
Label lStartDate = new Label();
pFullInfo_lStartDateStr.Controls.Add(lStartDate);
ImageButton ibEditStartDate = new ImageButton();
ibEditStartDate.ID = "ibEditStartDate_" + this_site_id;
pFullInfo_lStartDateStr.Controls.Add(ibEditStartDate);
TextBox tbEditStartDate = new TextBox();
pFullInfo_lStartDateStr.Controls.Add(tbEditStartDate);
tbEditStartDate.ID = "tbEditStartDate_" + this_site_id;
Image iEditStartDateCalendar = new Image();
iEditStartDateCalendar.ID = "iEditStartDateCalendar";
iEditStartDateCalendar.ImageUrl = "~/i/small/calendar.png";
iEditStartDateCalendar.ImageAlign = ImageAlign.AbsMiddle;
pFullInfo_lStartDateStr.Controls.Add(iEditStartDateCalendar);
CalendarExtender ceEditStartDate = new CalendarExtender();
ceEditStartDate.ID = "ceEditStartDate_" + this_site_id;
ceEditStartDate.PopupButtonID = iEditStartDateCalendar.ID;
ceEditStartDate.TargetControlID = tbEditStartDate.ID;
ceEditStartDate.PopupPosition = CalendarPosition.Right;
pFullInfo_lStartDateStr.Controls.Add(ceEditStartDate);
So what I did basicaly, I assigned an ID's to the TextBox and Image which are been used for the calendar, and that worked :]
Many thanks to Stack Overflow :]

how to assign target control to validator control on serverside

I am having N numbers of Text boxes those are generating dynamically. I want to validate each textbox for Formate HH:MM:SS PM/AM so i dynamicaly create the validation control . but as the dynamic textbox has no ID , so what i have to pass to the Validation control for ControlToValidate Property ?
AccordionPane ap1;
for (int i = 0; i <= 2; i++)
{
ap1 = new AccordionPane();
ap1.HeaderContainer.Controls.Add(new LiteralControl("Using Markup"));
Panel pnl = new Panel();
TextBox txtTime = new TextBox();
txtTime.ID = "txtTimeBox" + i;
txtTime.ValidationGroup = "MKE";
RegularExpressionValidator validateDate = new RegularExpressionValidator();
validateDate.ValidationExpression = "(0[1-9]|1[0-2]):([0-5][0-9]):([0-5][0-9]|60) (AM|PM|am|pm)";
validateDate.ControlToValidate = txtTime.ID;
validateDate.ErrorMessage = "Invalid Date. Try in HH:MM:SS AM/am|PM/pm format";
pnl.Controls.Add(txtTime);
ap1.ContentContainer.Controls.Add(pnl);
MyAccordion.Panes.Add(ap1);
}
Page.Controls.Add(divContainer);

Resources