访问动态创建的控件C#

时间:2015-07-22 18:46:24

标签: c# controls

我一直在阅读,发现一些事情很接近,但在我的情况下没有任何作用。用户有一个他们使用的设置文件,我将其读入Windows窗体。一个选项卡有2个标准列,但是那两个之后可以有更多的数字,它们具有基于标签的不同标签和列表框名称(即,如果标签是" portland"相应的列表框是&# 34; lstportland"但这些名称会有所不同)。在动态中创建了部分设置文件导入方法:

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

在Later方法中,我需要将动态创建的每个列表框的项目读入其自己的数组中,或以某种方式访问​​列表框本身中的项目。我已经草拟了以下内容,但它不起作用。有什么想法吗?

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

1 个答案:

答案 0 :(得分:3)

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

变化:

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

要:

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

搜索以获取控件,如评论中drzounds提供的链接。