Thread: dynmanic labels
View Single Post
  #2 (permalink)  
Old November 26th, 2008, 01:00 PM
dparsons dparsons is offline
Wrox Author
Points: 13,255, Level: 49
Points: 13,255, Level: 49 Points: 13,255, Level: 49 Points: 13,255, Level: 49
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Oct 2005
Location: Ohio, USA
Posts: 4,104
Thanks: 1
Thanked 64 Times in 64 Posts
Send a message via AIM to dparsons
Default

Actually creating the labels isn't really that difficult. Assume that you have a placeholder on your form named phControls your code would look something like this:

(Assume dt is a DataTable object)
for(int i = 0; i < dt.Rows.Count();i++)
{
   Label lbl = new Label();
   lbl.ID = "lbl" + Convert.ToString(i);
   lbl.Text = Convert.ToString(dt.Rows[i]["SomeColumn"]);
   phControls.Controls.Add(lbl);
}

This is pretty simple, however, if you run the code as is you will only see the last label added to the placeholder because each label in the code above would be placed in the exact same position within the placeholder, effectively stacking subsequent labels on top of one another.

To over come this assign values to the Top and Left properties of the label so:
lbl.Top = 10;
lbl.Left = 15;

Obviously you will need to change these values on each iteration of the loop but this should give you a good starting point.

hth.
-Doug

================================================== =========
Read this if you want to know how to get a correct reply for your question:
http://www.catb.org/~esr/faqs/smart-questions.html
================================================== =========
.: Wrox Technical Editor / Author :.
Wrox Books 24 x 7
================================================== =========
Reply With Quote