【问题标题】:handle onclick event in picturebox created on runtime处理在运行时创建的图片框中的 onclick 事件
【发布时间】:2014-05-15 03:05:22
【问题描述】:

我正在用 c# 编写 windows 窗体应用程序。

首先我在运行时创建了一个表格布局,然后在从数据库读取后插入图片框。现在我想在每个桌面单元格/图片框点击上编写 sql 查询。

首先,我尝试通过拖放插入图片框,然后在 picturebox_onclick 函数中编写查询。但是现在我正在运行时动态创建图片框。现在我如何处理我在运行时创建的图片框的 onclick 功能。

private void GenerateTable(int columnCount, int rowCount)
{
   //Clear out the existing controls, we are generating a new table layout
   tableLayoutPanel1.Controls.Clear();

   //Clear out the existing row and column styles
   tableLayoutPanel1.ColumnStyles.Clear();
   tableLayoutPanel1.RowStyles.Clear();

   //Now we will generate the table, setting up the row and column counts first
   tableLayoutPanel1.ColumnCount = columnCount;
   tableLayoutPanel1.RowCount = rowCount;

   for (int x = 0; x < columnCount; x++)
   {
      //First add a column
      tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));

      for (int y = 0; y < rowCount; y++)
      {
         //Next, add a row.  Only do this when once, when creating the first column
         if (x == 0)
         {
            tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize));
         }

         //Create the control, in this case we will add a button
         picturebox cmd = new picturebox();
         cmd.image = new bitmap("c:\\images\\abc.png");
         tableLayoutPanel1.Controls.Add(cmd, x, y);
      }
   }
}

请建议我简单的方法,因为我是开发新手。提前致谢。

【问题讨论】:

    标签: c# winforms tablelayout tablelayoutpanel


    【解决方案1】:

    这应该为你做。

    PictureBox cmd = new PictureBox();
    cmd.Click += cmd_Click;
    

    然后有一个新的函数来处理点击。

        void cmd_Click(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }  
    

    要根据点击的 PictureBox 执行独特的操作,您可能需要为 PictureBox 指定一个您可以关联的名称,例如行号或行的唯一 ID。

    PictureBox cmd = new PictureBox();
    cmd.Click += cmd_Click;
    cmd.Name = y.ToString();
    
        void cmd_Click(object sender, EventArgs e)
        {
            string RowID = ((PictureBox)sender).Name;
        }  
    

    【讨论】:

    • Ssc456...感谢您的回复...我想问一下 cmd.click 是否会存储该功能,每次我单击该图像时...它将调用该功能.. ?
    • 是的,没错。您分配一次函数,每次单击图像时都会调用它。
    • += 是在 C# 中将函数分配给动作的方式。 cmd.Click = cmd_Click;行不通。
    • 但是所有的图片框点击事件都会调用相同的函数...我想获取针对数据库中每个图片框保存的不同记录..
    • 好的,在这种情况下,我会为您的 PictureBoxes 提供唯一名称并根据它们的名称对其执行操作,请参阅我编辑的答案。
    猜你喜欢
    • 2021-09-22
    • 1970-01-01
    • 2014-02-01
    • 2023-04-10
    • 1970-01-01
    • 2017-03-14
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    相关资源
    最近更新 更多