简体   繁体   中英

C# Open Form from another Form Error

In Form1.cs i have

public const int n = 30;
public TabPage[] tp = new TabPage[n];

private void toolStripSeparator1_Click(object sender, EventArgs e)
{
    RenameFunc rf = new RenameFunc();
    rf.ShowDialog();
}

In RenameFunc.cs i have

private void button1_Click_1(object sender, EventArgs e)
{
    Form1 frm1 = new Form1();

    if (textBox1.Text != null)
    /*Line 24 */    frm1.tp[Array.IndexOf(frm1.tp, frm1.tabControl1.SelectedTab)].Text = textBox1.Text;
    Application.Exit();

}

tabControl1 is also seted tu Public

in Line 24 i get error

System.NullReferenceException: Object reference not set to an instance of an object. at System.Windows.Forms.TabControl.get_SelectedTabInternal() at System.Windows.Forms.TabControl.get_SelectedTab() at Notepad1._0.RenameFunc.button1_Click_1(Object sender, EventArgs e) in D:\\C#\\Notepad1.0\\Notepad1.0\\RenameFunc.cs:line 24

How to correct ?

I don't know what tp is, but, I'm sure it's not initialized and this gives the exception.
The reason is easily found in the previous line

Form1 frm1 = new Form1();

here you create a new instance of Form1. You are not referencing the first Form1 from which your RenameFunc has been called.

Perhaps you could pass a reference to the correct Form1 when you call RenameFunc, for example

RenameFunc rf = new RenameFunc(this); 

and keep that reference in your RenameFunc internal vars

public partial class RenameFunc : Form
{
    private Form1 _caller = null;
    public RenameFunc(Form1 f)
    {
         InitializeComponent();
         _caller = f;       
    }

}

and in button1_Click_1 use that reference instead of new Form1

   if (textBox1.Text != null)           
        _caller.tp[Array.IndexOf(_caller.tp, _caller.tabControl1.SelectedTab)].Text =
                   textBox1.Text;           
   Application.Exit();       

However a little explanation on tp would be beneficial

You can do as follows,

 Form1 frm = (Form1)this.Parent;

You can access controls using frm.Controls and do wat u like to do with it.

它返回错误,告诉您在frm1.tabControl1.SelectedTab中找不到frm1.tp ,您的代码都没有将tp中的30个选项卡与您显示的tabControl1关联,因此,将form1的新副本作为frm1 ,然后在寻找选中内容时要求在文本框中放置选项卡页的名称,答案是,没有选择那些新页面。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM