Reputation: 1
I'm making a program that lets you open any form in a folder in the project, by clicking its name in a listview.
My problem is that I can't seem to find a way to load/create a Form from a file/FileInfo Object
I'm wondering wether there is a better way to load the forms in to a list, that would make it easier to load a form?
PS: The point is to not know the form names in advance, or have to do any code to be able to open the form.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1 {
public partial class FolderList : Form {
FolderReader fr;
List<FileInfo> fileList;
public FolderList() {
InitializeComponent();
fr = new FolderReader();
}
private void Form1_Load(object sender, EventArgs e) {
this.MinimumSize = new System.Drawing.Size(this.Width, this.Height);
this.MaximumSize = new System.Drawing.Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
this.AutoSize = true;
this.AutoSizeMode = AutoSizeMode.GrowAndShrink;
fileList = fr.Read();
foreach (FileInfo file in fileList) {
ListViewItem item = new ListViewItem(file.Name);
item.Tag = file;
LVApps.Items.Add(item);
}
}
private void HandleDoubleClick(object sender, MouseEventArgs e) {
ListViewItem selected = LVApps.SelectedItems[0];
FileInfo fi = (FileInfo)selected.Tag;
//Here i would like to open a form from the file given above
Debug.WriteLine(fi.Name);
}
}
}
Folder reader :
public List<FileInfo> Read() {
String dir = Directory.GetCurrentDirectory();
dir = dir.Substring(0, dir.Length - 9);
dir = dir + "Forms";
Debug.WriteLine(dir);
List<FileInfo> fileList = new List<FileInfo>();
DirectoryInfo di = new DirectoryInfo(dir);
FileInfo[] files = di.GetFiles("*.cs");
foreach (FileInfo file in files) {
if (!file.FullName.Contains("Design")) {
fileList.Add(file);
}
return fileList;
}
return null;
}
Upvotes: 0
Views: 105
Reputation: 94
This looks to be what you are looking for:
var form = Activator.CreateInstance(Type.GetType("WindowsFormsApp1." + fi.Name)) as Form; form.ShowDialog();
from: https://stackoverflow.com/a/37523007/7911333
Upvotes: 2