简体   繁体   中英

Adding objects during run time?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM