0

I am getting all "Form Name" from project A into project B as per given in

C# Get form names of project A from Project B

and I am using @jerry's answer.

when my code reached var f = (Form)emptyCtor.Invoke(new object[] { }); line I am getting Exception has been thrown by the target of an invocation Error.

below is full code

try
{
    Assembly projectA = Assembly.Load("ProjectA"); // replace with actual ProjectA name 
    // despite all Microsoft's dire warnings about loading from a simple name,
    // you should be fine here as long as you don't have multiple versions of ProjectA
    // floating around

    foreach (Type t in projectA.GetTypes())
    {
        if (t.BaseType == typeof(Form))
        {
            var emptyCtor = t.GetConstructor(Type.EmptyTypes);
            if (emptyCtor != null)
            {
                var f = (Form)emptyCtor.Invoke(new object[] { });
                // t.FullName will help distinguish the unwanted entries and
                // possibly later ignore them
                string formItem = t.FullName + " // " + f.Text + " // " + f.Name;
                checkedListBox1.Items.Add(formItem);
            }
        }
    }
}
catch(Exception err)
{
    // log exception
}

I was searched Error reason but failed. please suggest me we I am worng

EDIT :

below are Error details

Image 1 Error1

Image 2

Err2

Community
  • 1
  • 1
Imran Ali Khan
  • 7,052
  • 15
  • 47
  • 74
  • 1
    Is there `InnerException` in error you get? – dewaffled Dec 25 '14 at 07:17
  • There's StackTrace in InnerException - you could have better understanding of what's wrong by examining it – J0HN Dec 25 '14 at 07:30
  • 2
    @J0HN InnerException stack trace indicates that exception is thrown by `FrmMachineryType` constructor. It seems you also have debug info (`.pdb` files ) for this assembly and stack trace should contain line number that throws the exception. If you have access to source code you can check what causes the error. Probably form constructor tries to access some static object that was not created. – dewaffled Dec 25 '14 at 09:19

2 Answers2

2

Try this:

var f = (Form)emptyCtor.Invoke(null);

BTW, what are you trying to achieve?

danish
  • 5,324
  • 2
  • 23
  • 28
2
private void childclick(object sender, EventArgs e)
{
    DataTable dtTrans = new DataTable();
    dtTrans = Db.bindData("SELECT frm_Code FROM tbl_MST_SubMnu WHERE frm_Name='" + sender.ToString() + "'");

    Assembly frmAssembly = Assembly.LoadFile(Application.ExecutablePath);
    foreach (Type type in frmAssembly.GetTypes())
    {
        if (type.BaseType == typeof(Form))
        {
            if (type.Name == dtTrans.Rows[0][0].ToString())
            {
                Form frmshow = (Form)frmAssembly.CreateInstance(type.ToString());

                frmshow.Show();
            }
        }
    }
}
Masoud Mohammadi
  • 1,523
  • 1
  • 20
  • 39
senthilkumar2185
  • 2,325
  • 3
  • 20
  • 31