如何引用在c#中创建运行时的控件?

时间:2017-04-25 20:00:21

标签: c# runtime

我的数据库中有2个表,其中一个表包含东西和其他价格。我设计了一个表单,它将事物名称检索为复选框,并为它们添加文本框。它们都是在表单加载时在运行时创建的。它们都在相应的循环中命名,当表单加载时,我可以看到它们以我想要的方式排列。但是我不能在表单的设计时间中引用它们,如下面TextBox1.Text所示。你可以建议我怎么做吗?谢谢你。下面是我为控件编写的代码:

public Form4()
    {
        InitializeComponent();

        SqlConnection conn = new SqlConnection("Data Source=ZEFIRAN\\SQLEXPRESS; Initial Catalog=Lab; Integrated Security=true");


        conn.Open();

        string say = "SELECT COUNT(DISTINCT Thing) FROM Sale";
        SqlCommand cmd = new SqlCommand(say, conn);

        Int32 ts = Convert.ToInt32(cmd.ExecuteScalar());

        conn.Close();

        for (int i = 0; i < ts; i++)
        {
            TextBox tb = new TextBox();
            tb.Width = 50;
            tb.Height = 25;
            tb.Name = "TextBox" + (i + 1).ToString();
            tb.Text = i + 1 + ". Test";
            panel1.Controls.Add(tb);
            int x = 150;
            int y = 40;
            tb.Location = new System.Drawing.Point(x, 40 + i * y);


        }

        for (int i = 0; i < ts; i++)
        {
            TextBox tb = new TextBox();
            tb.Width = 50;
            tb.Height = 25;
            tb.Name = "TextBox" + (2 * i + 1).ToString();
            tb.Text = i + 1 + ". Test";
            panel1.Controls.Add(tb);
            int x = 210;
            int y = 40;
            tb.Location = new System.Drawing.Point(x, 40 + i * y);
        }


        List<string> seyler = new List<string>();

        conn.Open();

        string query = "SELECT Thing FROM Things ORDER BY TNo";
        using (SqlCommand cmdtest = new SqlCommand(query, conn))
        {
            using (SqlDataReader dr = cmdtest.ExecuteReader())
            {
                while (dr.Read())
                {
                    seyler.Add(dr.GetString(0));
                }
            }

        }



        string toplam = "SELECT COUNT(Thing) FROM Things";

        SqlCommand tplm = new SqlCommand(toplam, conn);
        Int32 top1 = Convert.ToInt32(tplm.ExecuteScalar());


        for (int j = 0; j < top1; j++)
        {
            CheckBox chb = new CheckBox();
            panel1.Controls.Add(chb);
            int t = 50;
            int u = 40;
            chb.Location = new System.Drawing.Point(t, 40 + j * u);
            chb.Width = 100;
            chb.Height = 25;
            chb.Text = seyler[j];
            chb.Name = "cb" + (j + 1).ToString();

        }

         conn.Close();

        TextBox1.Text = "";

    }    

0 个答案:

没有答案