0

Background

I have a tab which is made active if there is more than one record returned from a query on my database.

For each record returned I would like a set of labels created and placed on the tab. For example if there are 8 records I would like 8 labels created.

Question

  1. My loop only creates one label, even though my count is showing I have 8 records? Not sure why?

  2. How do you create labels in a loop 8 times and not have them draw in the same location 8 times? I would them to appear in a horizontal list. Pretty sure the way I have coded the solution ,they will all be drawn in the same place?

Code

for (int i = 1; i <= rowCount; i++)
{      
    // Create objects 
    LinkLabel Linklabel1 = new LinkLabel();
    Linklabel1.Text += ds.Tables[0].Rows[0]["code"].ToString();
    Linklabel1.Location = new Point(10, 50);
    Linklabel1.Height = 40;
    Linklabel1.Width = 100;
    tabControl1.TabPages[0].Controls.Add(Linklabel1);       
}
4
  • 1
    set the location using something relative to the i indexer. e.g Location = new Point(10, 50 + (i*10)); Commented Jan 25, 2015 at 16:12
  • 2
    You have 8 labels. They are just occupying the same spot, at coords 10x50. Add 26*i to x and you should be fine. Commented Jan 25, 2015 at 16:13
  • @Darek, did what you suggested, however it doesn't work. Shouldn't the name change too? Otherwise you'll just be redrawing the same label 8 times, but only the last one being visible? Commented Jan 25, 2015 at 16:27
  • @ASh I meant the name of the labels. Commented Jan 25, 2015 at 16:38

1 Answer 1

1

Try something like this out:

        for (int i = 0; i < rowCount; i++)
        {
            // Create objects 
            LinkLabel Linklabel1 = new LinkLabel();
            Linklabel1.Text = ds.Tables[0].Rows[i]["code"].ToString();
            Linklabel1.Height = 40;
            Linklabel1.Width = 100;
            Linklabel1.Location = new Point((i + 1) * 10 + (i * Linklabel1.Width), 50);
            tabControl1.TabPages[0].Controls.Add(Linklabel1);
        }

If you don't want to explicitly position them by setting the Location() property, consider putting a FlowLayoutPanel on the TabPage and added the controls to that instead. Then they will positioned automatically for you.

Sign up to request clarification or add additional context in comments.

2 Comments

Would you mind explaining this line please? Linklabel1.Location = new Point((i + 1) * 10 + (i * Linklabel1.Width), 50);
That moves the control to the right and gives a 10 pixel gap between them. i = 0, x = 10 | i = 1, x = 120 | i = 2, x = 230 | i = 3, x = 340 | etc...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.