标签控件内的FlowLayoutPanel

我在每个选项卡中都有一个tabControl和flowLayoutPanel.当我将文件拖放到选项卡上时,它将创建一个按钮,其中包含文件的图标.但是我可以选择创建更多选项卡,并且我希望能够将文件拖到所选选项卡中.但是问题是添加按钮时的flowLayoutPanel.

到目前为止,我的代码:

   public Process myProcess = new Process();
   FlowLayoutPanel fl_panel = new FlowLayoutPanel();

    string path_app;

    public Form1()
    {

        InitializeComponent();
     //add the flowLayoutPanel on the first tab
        fl_panel.Dock = DockStyle.Fill;
        fl_panel.BringToFront();
        tabPage1.Controls.Add(fl_panel);

        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);
                fl_panel.Controls.Add(button);
                path_app = String.Format("{0}", s);
                button.Tag = path_app;
                string filename = path_app;
                Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(filename);
                Bitmap bmp = icon.ToBitmap();
                button.BackgroundImage = bmp;
                button.Width = 60;
                button.Height = 75;
                button.FlatStyle = FlatStyle.Flat;
                button.BackgroundImageLayout = ImageLayout.Stretch;

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

    }

   private void add_tab_btn_Click(object sender, EventArgs e)
    {

       //Create new tab with FLP inside
        string title = Convert.ToString(textBox1.Text);
        TabPage new_TabPage = new TabPage(title);
        fl_panel.Dock = DockStyle.Fill; 
        fl_panel.BringToFront();
        new_TabPage.Controls.Add(fl_panel);
        tabControl1.TabPages.Add(new_TabPage);
    }
}

如果我使用fl_panel.Controls.Add(button);它会在第一个选项卡上很好地添加按钮,但是如果我创建一个新选项卡,我不知道如何将tabControl.SelectedTab与fl_panel.Controls.Add(button)一起使用,以将按钮正确地添加到所选选项卡上.

解决方法:

您必须为每个选项卡创建一个新的FlowLayoutPanel:

FlowLayoutPanel fl_panel = new FlowLayoutPanel();
...
new_TabPage.Controls.Add(fl_panel);

然后,您可以将TabPage的第一个元素转换为FlowLayoutPanel并从那里访问控件:

FlowLayoutPanel selectedFLP = (FlowLayoutPanel)tabControl.SelectedTab.Controls[0];
...
上一篇:删除/编辑TabPages的TabControl填充


下一篇:C#-在flowLayoutPanel中重新排列CustomControl