Add Row Dynamically in TableLayoutPanel

后端 未结 4 751
名媛妹妹
名媛妹妹 2020-12-14 00:29

\"enter

I want to add these entries dynamically row by row in TableLayoutPanel in Wind

4条回答
  •  感情败类
    2020-12-14 01:15

    I know that this question is very old, but someone could find the following as useful:

    First of all, note that petchirajan's answer is good, but if you have at least one existent row (titles, for example) and you want to continue the list using the height set using visual editor, and without having to modify the code, you can use this:

    private void AddItem(string address, string contactNum, string email )
        {
            //get a reference to the previous existent 
            RowStyle temp = panel.RowStyles[panel.RowCount - 1];
            //increase panel rows count by one
            panel.RowCount++;
            //add a new RowStyle as a copy of the previous one
            panel.RowStyles.Add(new RowStyle(temp.SizeType, temp.Height));
            //add your three controls
            panel.Controls.Add(new Label() {Text = address}, 0, panel.RowCount - 1);
            panel.Controls.Add(new Label() { Text = contactNum }, 1, panel.RowCount - 1);
            panel.Controls.Add(new Label() { Text = email }, 2, panel.RowCount - 1);
        }
    

    If you prefer a generic method for a generic table:

    private void AddRowToPanel(TableLayoutPanel panel, string[] rowElements)
        {
            if (panel.ColumnCount != rowElements.Length)
                throw new Exception("Elements number doesn't match!");
            //get a reference to the previous existent row
            RowStyle temp = panel.RowStyles[panel.RowCount - 1];
            //increase panel rows count by one
            panel.RowCount++;
            //add a new RowStyle as a copy of the previous one
            panel.RowStyles.Add(new RowStyle(temp.SizeType, temp.Height));
            //add the control
            for (int i = 0; i < rowElements.Length; i++)
            {
                panel.Controls.Add(new Label() { Text = rowElements[i] }, i, panel.RowCount - 1);
            }
        }
    

    You can do this also using a Collection instead of an array using:

     private void AddRowToPanel(TableLayoutPanel panel, IList rowElements)
        ...
    

    Hope this helps.

提交回复
热议问题