Loop through the labels of a page to assign text - asp.net

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");

Related

How to create a table from CodeBehind using ASP.NET Table Control methods (using, Table,TableRow,TableColumn,TableHeader etc.)

I need to create a table, which will have one header and Like This multiple checkboxes. Can someone please give some reference so that I can understand how ASP.NET table control works. I already went thorough MSDN blog. So but I was unable understand that. I will be very happy if someone can explain in details.
Can't see your image because work blocks imgur.com, so hopefully this helps. We use something like this to create custom ListView Controls. But since you can't use a GridView, I would suggest putting a PlaceHolder control on the page. Once the table is created then add it to the PlaceHolder.
Table t = new Table();
TableHeaderRow th = new TableHeaderRow();
//add the header row to table t
t.Rows.Add(th);
//add three columns to the header row with a label for text
for (int i = 0; i < 3; i++)
{
TableCell td = new TableCell();
Label lb = new Label();
lb.Text = "Header Label: " + i.ToString();
td.Controls.Add(lb);
th.Cells.Add(td);
}
//add the rows, say you need five
for (int i = 0; i < 5; i++)
{
TableRow tr = new TableRow();
//add three columns to the table row with a checkbox
for (int i = 0; i < 3; i++)
{
//add the cells with a checkbox
TableCell td1 = new TableCell();
CheckBox cb = new CheckBox();
cb.Text = "CheckBox: " + i.ToString() + "_" + j.ToString();
td.Controls.Add(cb);
tr.Cells.Add(td1);
}
t.Rows.Add(tr);
}
placeHolder.Controls.Add(t);

Visual Studios ASPX. Using Panels to create Controls dynamically in a column

I have a list filled with objects and for each object, I would like to create a new label at run-time. I would like the labels to be stacked on top of each other and not side by side.
for (int i = 0; i < list_product.Count; i++)
{
int labelCount = 1;
Label newLabel = new Label();
newLabel.ID = "newLabel" + labelCount;
newLabel.Text = list_product[i].ProductName;
labelCount++;
panel_test.Controls.Add(newLabel);
}
I've been looking everywhere and I can't find a solution. Thanks for your help!

how to add picture box control and label control dynamically in list view control

I want to display picture box control and label into list view for particular record. And all the records comes from the database. I tried it but i am only able to display only single image but i want to display all images with label
the code I try is
DataSet ds3 = load.LoadNewlyAddedBook();
DataTable dt3 = ds3.Tables[0];
lstViewNewAdd.Items.Clear();
int count = dt3.Rows.Count;
for (int a = 0; a < count; a++)
{
DataRow dtRow = dt3.Rows[a];
if (dtRow.RowState != DataRowState.Deleted)
{
ListViewItem lvi3 = new ListViewItem(dtRow["BookName"].ToString());
PictureBox p1 = new PictureBox();
p1.Size = new Size(80, 100);
Byte[] bytes = (Byte[])(dtRow["BookImage"]);
MemoryStream ms = new MemoryStream(bytes);
p1.Image = Image.FromStream(ms);
p1.SizeMode = PictureBoxSizeMode.StretchImage;
Label lbl = new Label();
lbl.Text = dtRow["BookName"].ToString();
lstViewNewAdd.Controls.Add(p1);
//lstViewNewAdd.Controls.Add(lbl);
//lvi3.SubItems.Add(p1);
//lstViewNewAdd.Items.Add(lvi3);
}
}
Please suggest me any solution.
Thanks in advance.
Did you google around?
There are lot of links that can help you
http://geekswithblogs.net/dotNETvinz/archive/2009/04/24/faq-displaying-image-from-database-to-gridview-control.aspx
http://weblogs.asp.net/aghausman/archive/2009/05/26/show-images-on-grid-view-from-file-stream.aspx
http://www.codeproject.com/Articles/20782/Displaying-Images-from-a-Database-in-a-GridView
http://www.codeproject.com/Articles/20971/Thumbnail-Images-in-GridView-using-C

Displaying data from DataReader in Label control (ASP.NET)

I have a query that returns one row so I want to display it in the Label, but I can't find the property DataSource on it.
How can I do this ?
If you're using a SqlDataReader in C# then you want something like this
string label;
if (reader.Read())
{
label = reader.IsDBNull(reader.GetOrdinal("Column"))
? String.Empty
: reader.GetString(reader.GetOrdinal("Column"));
}
reader.Close();
MyLabel.Text = label;
In VisualBasic.Net it will be something like
Dim label as String
If reader.HasRows Then
Label = reader.GetString(reader.GetOrdinal("ColumnName"))
End If
reader.Close
MyLabel.Text = label
If you are only returning one row with one column you might want to use command.ExecuteScalar() instead of a data reader. Then you can just set your label like this:
lblAnswer.Text = myCommand.ExecuteScalar().ToString()
I know this is a bit old thread, but the above did not work for me. But this did:
If reader.HasRows Then
label = reader("columnName")
labelName.Text = label
End If
smc

How to create line breaks between dynamically generated labels in a placeholder?

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.

Resources