我来询问是因为我是 Windows 窗体的新手,我需要一些帮助。
我有一个包含 2 个窗体的 Windows 窗体项目。 MainForm 和 InnerForm。
我正在尝试从 InnerForm 访问 MainForm 中的 TableLayoutPanel,以在此 tablelayoutpanel 中添加新行,并执行 InnerForm 中发生的一些操作。
我有下一个代码:
主窗体:
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
TableLayoutPanel panel = tableLayoutPanel1;
panel.ColumnCount = 4;
panel.RowCount = 1;
panel.RowStyles.Add(new RowStyle(SizeType.AutoSize, 0));
panel.Controls.Add(new Label() { Text = "Tag/ID" }, 0, 0);
panel.Controls.Add(new Label() { Text = "Tipo" }, 1, 0);
panel.Controls.Add(new Label() { Text = "Acción" }, 2, 0);
panel.Controls.Add(new Label() { Text = "Ejecutar" }, 3, 0);
}
private void AddInnerForm(string url)
{
var inner = new InnerForm(url)
// more code
}
public void agregarRow(ConsoleMessageEvents args){
// some action with tableLayoutPanel1
}
}
内部表格:
public partial class InnerForm : UserControl
{
MainForm theMain;
public InnerForm(MainForm main)
{
theMain = main;
}
public InnerForm(string url)
{
InitializeComponent();
// more code
}
private void OnBrowserConsoleMessage(object sender, ConsoleMessageEventArgs args)
{
theMain.agregaRow(args);
}
}
但是当我调试程序时,我收到此错误:
An unhandled exception of type 'System.NullReferenceException' occurred in Project.exe
Additional information: Object reference not set to an instance of an object.
在 InnerForm 的这一行中:
private void OnBrowserConsoleMessage(object sender, ConsoleMessageEventArgs args)
{
**theMain.agregaRow(args)**;
}
这里有什么问题吗?
最佳答案
这应该可以解决问题。 theMain 字段未初始化,还需要在每个构造函数中调用 InitializeComponenets 来创建子控件。
public partial class InnerForm : UserControl
{
MainForm theMain;
public InnerForm(MainForm main)
{
InitializeComponent();
theMain = main;
}
public InnerForm(string url, MainForm mainForm)
{
this.theMain = mainForm;
InitializeComponent();
// more code
}
private void OnBrowserConsoleMessage(object sender, ConsoleMessageEventArgs args)
{
theMain.agregaRow(args);
}
}
在主窗体中:
private void AddInnerForm(string url)
{
var inner = new InnerForm(url, this)
// more code
}
关于时间:2019-01-17 标签:c#Windowsforms 'Object reference not set to an instance of an object',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29303468/