c#中的动态按钮,文本和图片框创建

时间:2013-07-31 07:41:37

标签: c# dynamic

我在这里做一个项目。图像中存在问题的地方。项目加载时,屏幕上会出现“开始检查”按钮。按下按钮后,它应该为指定路径中的每个图像创建图片框,文本框和按钮。然后用户必须在动态创建的文本框中输入答案。单击每个图像的动态提交按钮后,文本框值必须存储在列表框中。我不知道如何从文本框中获取值。任何人都可以帮助我解决这个问题。

这是我的编码:

PictureBox[] pics = new PictureBox[100];
TextBox[] txts = new TextBox[100];
Button[] butns = new Button[100];
FlowLayoutPanel[] flws = new FlowLayoutPanel[100];

private void button1_Click( Object sender , EventArgs e)
{
        for (int i = 0; i < listBox1.Items.Count; i++)
        {
            flws[i] = new FlowLayoutPanel();
            flws[i].Name = "flw" + i;
            flws[i].Location = new Point(3,brh);
            flws[i].Size = new Size(317,122);
            flws[i].BackColor = Color.DarkCyan;
            flws[i].BorderStyle = BorderStyle.Fixed3D;
            pics[i] = new PictureBox();
            pics[i].Location = new Point(953, 95 + brh);
            pics[i].Name = "pic" + i;
            pics[i].Size = new Size(300, 75);
            pics[i].ImageLocation = "C:/" + listBox1.Items[i];
            flws[i].Controls.Add(pics[i]);

            txts[i] = new TextBox();
            txts[i].Name = "txt" + i;
            txts[i].Location = new Point(953, 186 + brh);

            flws[i].Controls.Add(txts[i]);
            butns[i] = new Button();
            butns[i].Click += new EventHandler(butns_Click);
            butns[i].Text = "submit";
            butns[i].Name = "but" + i;
            butns[i].Location = new Point(1100, 186 + brh);

            flws[i].Controls.Add(butns[i]);
            flowLayoutPanel1.Controls.Add(flws[i]);
            brh += 130;



        }
     }
private void butns_Click(object sender, EventArgs e)
{
    Button butns = sender as Button;
    TextBox txts = sender as TextBox;

    listBox2.Items.Add("text values " + txts.Text.ToString());
}

2 个答案:

答案 0 :(得分:0)

我会创建一个usercontrol来组合控件。

搜索“custom usercontrol c#”

问候。

答案 1 :(得分:0)

试试这个......

 private void butns_Click(object sender, EventArgs e)
    {
        Button butns = sender as Button;
        string btnName = butns.Name;
        string Id = btnName.Substring(3);
        string txtName = "txt" + Id;
        listBox2.Items.Add("text values " + GetValue(txtName));
    }

    private string GetValue(string name)
    {
        TextBox txt = new TextBox();
        txt.Name = name;
        foreach (Control ctl in this.Controls)
        {
            if (ctl is FlowLayoutPanel)
            {
                foreach (Control i in ctl.Controls)
                {
                    if (((TextBox)i).Name == txt.Name)
                    {
                        txt = (TextBox)i;
                        return txt.Text;
                    }
                }
            }
        }
        return txt.Text;
    }
}