将参数传递给循环中的事件

时间:2014-03-11 18:50:23

标签: c# winforms events event-handling parameter-passing

我已从数据库中加载了一些带有图像位置的Picturebox,我想将参数(价格和名称)传递给循环中的单击事件处理程序

代码如下所示:

private void Caisse_Load(object sender, EventArgs e)
    {

        int repetition = 0;
        int rep = 1;
        textMontant.Text = mont;
        SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Test"].ToString());
        con.Open();
        SqlCommand cmd = new SqlCommand( "select desig_prd,prix_prd ,image from Produit ",con);

       using (SqlDataReader reader1 = cmd.ExecuteReader())
       {
           while (reader1.Read())
           {
               if (repetition % 3== 0)
                   repetition = 0;

               PictureBox p = new PictureBox();

              p.Click += new System.EventHandler(P_Click(sender, 
              new MyEventArgs { design = reader1["desig_prd"].ToString(), prix = (float)reader1["prix_prd"] }));

               p.ImageLocation = reader1["image"].ToString();

              p.Height = 100;
              p.Width = 160;
              p.Location = new System.Drawing.Point(4+ repetition * 150, (int)(rep/4)*130+4);

               panel1.Controls.Add(p);
               repetition++;
               rep++;
           }


       }   
    }

点击图片框下方我希望传递2个参数(价格:reader1 [“prix_prd”]和产品名称:reader1 [“desig_prd”]),不要忘记它们处于循环中! 我知道

 p.Click += new System.EventHandler(P_Click(sender, 
              new MyEventArgs { design = reader1["desig_prd"].ToString(), prix = (float)reader1["prix_prd"] }));

触发错误“预期的事件名称”但是如何在循环中将参数传递给事件? 提前致谢

2 个答案:

答案 0 :(得分:5)

您无法将自定义参数传递给Click事件处理程序,因为您不是引发此事件的人...

但是,您可以使用匿名方法或lambda表达式来指定捕获必要数据的处理程序:

var design = reader1["desig_prd"].ToString();
var prix = (float)reader1["prix_prd"];
p.Click += (sender1, e1) => SomeMethod(design, prix);

答案 1 :(得分:0)

使用lambda来关闭相关变量:

string design = reader1["desig_prd"].ToString();
fload prix = (float)reader1["prix_prd"];
p.Click += (s, args) => P_Click(p,
    new MyEventArgs
    {
        design = design,
        prix = prix,
    });