如何为动态创建的元素设置不同的事件

时间:2014-12-14 18:51:35

标签: c# asp.net .net

我试图为动态创建的GroupBox创建具有不同索引的事件。每个groupbox的实际代码事件都是一样的。如何为每个组框创建不同索引的事件?我的代码:

public void LoadGry()
        {

           // GroupBox groupbox = new GroupBox();
            Label nazwagry = new Label();
            for(int i = 0; i < myCollection.Count; i++)
            {
                GroupBox groupbox = new GroupBox();
                groupbox.Text = myCollection[i];
                groupbox.Size = new Size(290, 131);
                groupbox.Location = new Point(6, 150 * (myCollection.Count - i - 1));
                groupbox.ForeColor = Color.White;
                Label label1 = new Label();
                label1.Text = groupbox.Text;
                label1.AutoSize = true;
                label1.Location = new Point(groupbox.Location.X + 80, groupbox.Location.Y + 20);
                groupbox.Controls.Add(label1);
                Gry.Controls.Add(label1);

                PictureBox picturebox = new PictureBox();
                picturebox.Location = new Point(groupbox.Location.X + 5, groupbox.Location.Y + 20);
                picturebox.Size = new Size(75, 75);
                picturebox.SizeMode = PictureBoxSizeMode.StretchImage;
                picturebox.LoadAsync(myCollection3[i]);
                groupbox.Click += new EventHandler(delegate {groupboxclick(groupbox, picturebox, i);});
                Label label2 = new Label();
                label2.Text = "Status: " + "Aktualny";
                label2.ForeColor = Color.Green;
                label2.AutoSize = true;
                label2.Location = new Point(label1.Location.X, label1.Location.Y + 20);
                Gry.Controls.Add(label2);
                Label zapiszopis = new Label();
                zapiszopis.Text = myCollection4[i];
                zapiszopis.Visible = false;

                Gry.Controls.Add((Control)groupbox);    

                //MessageBox.Show("pokaz mi wysokosc");
                }
            }
private void groupboxclick(GroupBox groupbox, PictureBox picturebox, int itest)
        {


            groupbox.ForeColor = Color.Aqua;
            this.pictureBox1.BackgroundImage = picturebox.BackgroundImage;
            opishacka.Text = myCollection4[itest];
        }

1 个答案:

答案 0 :(得分:1)

问题是事件设置使用变量K值。要使用数字,您可能需要手动创建表达式以在每种情况下使用当前值。

BUT 您可以使用以下属性轻松执行所需操作,以将值附加到控件。

1-)WinForms&amp;中的标签WPF:

// Setup
pictureBox.Tag = i;

// Event
int i = (int) pictureBox.Tag;

2-)WebForms中的ViewState

// Setup
ViewState[pictureBox.UniqueID] = i;

// Event
int i = (int) ViewState[pictureBox.UniqueID];

您可以使用许多其他技巧。我只为每个流行的框架发布一个。我邀请您参加WinFors项目。

希望这有帮助!