c# - 为多个按钮注册一个点击事件并为每个按钮传递不同的值

标签 c# winforms button procedural-generation

我根据列表中的内容程序生成按钮,该列表包含文件路径。我需要每个按钮使用以下路径从路径中打开特定文件: System.Diagnostics.Process.Start(文件路径)

但是,button.Click = 要求它运行的函数是 System.EventHandler,而打开文件的代码是 System.Diagnostics。处理

下面是生成按钮的代码:

 private int importButtonFactory()
    {
        int numberOfButtons = 0;

        int top = 70;
        int left = 100;

        foreach (Import import in ImportList)
        {
            Button button = new Button();
            button.Left = left;
            button.Top = top;
            this.Controls.Add(button);
            top += button.Height + 2;
            numberOfButtons++;
            button.Text = import.Scheme;
            button.Click += openFile_Click(import.Path);
        }

        return numberOfButtons;
    }

button.Click“openFile_Click()”的函数:

        private void openFile_Click(string filePath)
        {
            System.Diagnostics.Process.Start(filePath);
        } 

这是我最初认为可以简单工作的方法,但是前一个函数中的函数提示错误:“无法将类型‘void’隐式转换为‘System.EventHandler’”如果我使该类型的函数尝试和请它说该函数不返回任何值....我不希望它这样做,但 System.EventHandler 似乎需要它。

我不确定是否有任何虚拟数据我可以让它作为 System.EventHandler 返回只是为了关闭它,或者有一个我不知道的正确方法让我的方案工作。

编辑:这是一个 Windows 窗体应用程序

最佳答案

您的事件处理程序必须与事件签名匹配。因此,您的按钮点击处理程序必须使用此签名:

private void Button_Click(object sender, System.EventArgs e)
{
}

现在要识别哪个 URL 属于哪个按钮,您可以给按钮一个标签,例如持有列表索引,假设它是一个 List<T>或另一个可索引的集合:

    for (int i = 0; i < ImportList.Count; i++)
    {
        // ...
        button.Text = ImportList[i].Scheme;
        button.Tag = i;
        button.Click += Button_Click;
    }

然后在您的点击处理程序中:

private void Button_Click(object sender, System.EventArgs e)
{
    Button button = sender as Button;
    int index = (int)button.Tag;

    var import = ImportList[index];

    Process.Start(import.Path); 
}

关于c# - 为多个按钮注册一个点击事件并为每个按钮传递不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34706811/

相关文章:

.net - 如何防止 Windows 窗体文本框在调整大小时闪烁?

iOS - TableView + 按钮布局(外部)

button - 如何在 flutter 中对齐按钮中的文本?

c# - 在单独的线程上执行进程会导致 System.IO.__Error.WinIOError

c# - 返回任务或等待和 ConfigureAwait(false)

c++ - OpenFileDialog->DialogShow() 结果导致 SQLite 出错

c# - 将 Windows 窗体单元测试迁移到 WPF

jquery - CSS装饰按钮变得不活动且不可点击

c# - 在简单注入(inject)器中注册具有构造函数参数的泛型类型

c# - 变量前缀 (“Hungarian notation” ) 真的有必要了吗?