C# - 创建动态按钮和事件

时间:2014-03-31 13:03:19

标签: c# events button tabcontrol flowlayoutpanel

我有一个带tabControl的表单,每个选项卡内部都有一个flowLayoutPanel,我可以在其中拖放文件,并为每个删除的文件创建一个按钮。之后当我点击一个按钮时,我删除的文件应该打开。我已经设法只为一个文件执行此操作..我的问题是如何判断单击了哪个按钮并打开存储在每个按钮的路径中的文件/应用程序..如何区分button_click事件中单击的按钮以及应用程序打开的路径?

到目前为止

此部分的代码:

Process myProcess = new Process();
string path_app;

public Form1()
{
   InitializeComponent();
   this.DragEnter += new DragEventHandler(Form1_DragEnter);
   this.DragDrop += new DragEventHandler(Form1_DragDrop);
}

void Form1_DragEnter(object sender, DragEventArgs e)
{
   if (e.Data.GetDataPresent(DataFormats.FileDrop, false))
      e.Effect = DragDropEffects.All;
}

void Form1_DragDrop(object sender, DragEventArgs e)
{
   string[] fileList = e.Data.GetData(DataFormats.FileDrop) as string[];

   foreach (string s in fileList)
   {

      Button button = new Button(); 
      button.Click += new EventHandler(this.button_Click);
      flowLayoutPanel1.Controls.Add(button);
      path_app = String.Format("{0}", s);
   }
}

private void button_Click(object sender, System.EventArgs e)
{
   myProcess.StartInfo.FileName =path_app;
   myProcess.Start();
} 

此外我的tabControl可以添加新选项卡但是如何获取选定的选项卡和内部flowLayoutPanel以了解创建按钮的位置?

顺便说一句,我是如何打开文件的?我明白我必须考虑工作目录..

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

您可以使用button.Tag = "theFancyPath"并在EventHandler中投射object sender as Button以访问Tag属性。

如果您需要更多,那么您可以从Button继承:

public class ButtonWithPathProperty : Button
{
    public FileInfo PathToOpen { get; private set; }

    public ButtonWithPathProperty(FileInfo path) 
    {
         PathToOpen = path;
         this.Click += new EventHandler(this.button_Click);
    }

    private void button_Click(object sender, System.EventArgs e)
    {
        var yourPath = this.PathToOpen;
    } 
}

这未经过测试btw:)

答案 1 :(得分:1)

您可以使用Tag的{​​{1}}属性:

Button