访问动态创建的控件 C#

accessing dynamically created controls C#

我读了一些书,发现有些东西很接近,但对我来说没有任何用处。用户有一个他们使用的设置文件,我将其读入 Windows 形式。一个选项卡有 2 个标准列,但是在这两个具有不同标签和基于标签的列表框名称之后可以有更多的数字(即,如果标签是 "portland",则相应的列表框是 "lstportland"但这些名称会有所不同)。在settings文件导入方法的is部分有created,on the fly:

 for (int i = 3; i < (lastColumn); i++)
        {
            //creates new list box and names it the column name with a "lst" infront of it
            var cellVal = squidSheet.Cells[1, i].Value;
            string convertString = cellVal.ToString();
            string listBoxName = "lst" + convertString;
            int lbLocation = new int();

            /*where to place the next label/listbox on the sheet based on a placement point  if its the first one
             *it is placed in a specific spot, then each subsequent one is placed equidistant from the last.*/
            if (i==3)
            { lbLocation = 382; }
            else
            { lbLocation = 382 + (115*(i-3)); }                

            //create the properties for the new listbox and label in its proper place on the "Run Tab"
            ListBox listBox1 = new ListBox();
            Label label1 = new Label();
            listBox1.Name = listBoxName;
            listBox1.Height = 316;
            listBox1.Width = 94;
            listBox1.Location = new Point(lbLocation, 30);

            label1.Location = new Point(lbLocation, 14);
            label1.Text = convertString;
            label1.Name = "lbl" + convertString;
            label1.Font = new Font("Microsoft Sans Serif", 8, FontStyle.Regular); 

            //add the new listbox and label to the Form
            tabPage4.Controls.Add(listBox1);
            tabPage4.Controls.Add(label1);

            //fill the new list box
            string colIdString = TestCase((i-1).ToString());
            fillListBox(listBox1, lastRowRunList, squidSheet, colIdString);
        }

在稍后的方法中,我需要将动态创建的每个列表框的项目读取到它自己的数组中,或者以某种方式访问​​列表框本身中的项目。我已经勾勒出以下内容,但它不起作用。有什么想法吗?

for (int l = 2; l < (listBoxNames.Count); l++)
                {                        
                    string variableNameString = labelText[l].ToString();
                    string variableNames = "#" + variableNameString + "#";
                    ListBox listboxTest = Controls[("lst" + variableNameString)] as ListBox;
                    string variableValues = listboxTest.Items[(l-1)].ToString();
                    readText = readText.Replace(variableNames, variableValues);
                }

找不到控件,因为您正在搜索 Form 的 Controls() 集合,而不是它的实际容器 tabPage4 .

变化:

ListBox listboxTest = Controls[("lst" + variableNameString)] as ListBox;

收件人:

ListBox listboxTest = tabPage4.Controls[("lst" + variableNameString)] as ListBox;

搜索作为drzounds在评论中提供的link中的控件。