[英]C# Open Form from another Form Error
In Form1.cs i have 在Form1.cs中,我有
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 在RenameFunc.cs中,我有
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 tabControl1也已设置为public
in Line 24 i get error 在第24行中,我得到了错误
System.NullReferenceException: Object reference not set to an instance of an object. System.NullReferenceException:对象引用未设置为对象的实例。 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 在Notepad1._0的System.Windows.Forms.TabControl.get_SelectedTab()的System.Windows.Forms.TabControl.get_SelectedTabInternal()处D:\\ C#\\ Notepad1.0 \\ Notepad1的RenameFunc.button1_Click_1(Object sender,EventArgs e) .0 \\ RenameFunc.cs:第24行
How to correct ? 如何纠正?
I don't know what tp
is, but, I'm sure it's not initialized and this gives the exception. 我不知道什么是tp
,但是,我确定它没有初始化,这会引起异常。
The reason is easily found in the previous line 原因很容易在上一行中找到
Form1 frm1 = new Form1();
here you create a new instance of Form1. 在这里,您将创建一个Form1的新实例。 You are not referencing the first Form1 from which your RenameFunc has been called. 您没有引用从中调用RenameFunc的第一个Form1。
Perhaps you could pass a reference to the correct Form1 when you call RenameFunc, for example 例如,也许在调用RenameFunc时可以传递对正确Form1的引用。
RenameFunc rf = new RenameFunc(this);
and keep that reference in your RenameFunc internal vars 并将该引用保留在您的RenameFunc内部变量中
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 在button1_Click_1中使用该引用代替新的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 但是对tp的一些解释将是有益的
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. 您可以使用frm.Controls
来访问控件,并喜欢使用它。
它返回错误,告诉您在frm1.tabControl1.SelectedTab
中找不到frm1.tp
,您的代码都没有将tp
中的30个选项卡与您显示的tabControl1
关联,因此,将form1
的新副本作为frm1
,然后在寻找选中内容时要求在文本框中放置选项卡页的名称,答案是,没有选择那些新页面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.