我正在尝试在C#中创建一个控件数组,但Visual Studio Express不合作。 我在运行时收到消息:
对象引用未设置为对象的实例。
错误发生在下面的箭头上。我如何使这项工作?
public partial class Protocoltool : Form
{
// ... other stuff
// doesn't seem to make instances as I expect it would
// class String_Entry is defined lower
public String_Entry[] pt_entries = new String_Entry[NB_ENTRIES];
// Constructor for class protocol tool
public Protocoltool()
{
InitializeComponent();
// tried to make instances here but still doesn't work
//pt_entries = new String_Entry[NB_ENTRIES];
// Add the supposedly instanciated control in a tableLayoutPanel
EntriesGuiAdd();
// ... other stuff
}
private void EntriesGuiAdd()
{
for (int i = 0; i < NB_ENTRIES; i++)
{
// tried to make instances here but still doesn't work
//pt_entries[i].Create();
// tried to make instances here directly, but still doesn't work
-----------&gt; pt_entries [i] .textbox = new System.Windows.Forms.TextBox(); pt_entries [i] .send = new System.Windows.Forms.Button();
//tableLayoutPanel1.Controls.Add(pt_entries[i].textbox, 0, i);
//tableLayoutPanel1.Controls.Add(pt_entries[i].send, 1, i);
}
}
} // end of protocoltool class
public class String_Entry
{
public TextBox textbox;
public Button send;
public int sequential_counter;
// A constructor here doesn't work at all
/*
... so I put the constructor here instead, but still it doesn't work
public void Create()
{
Console.WriteLine("creating entry");
// tried to make instances here but still doesn't work
textbox = new TextBox();
send = new Button();
send.Click += new System.EventHandler(this.bSend_Click);
}
*/
// ... other functions
}
答案 0 :(得分:0)
您需要初始化pt_entries[i]
,然后才能引用它的任何属性。
pt_entries[i] = new String_Entry();
pt_entries[i].textbox = new System.Windows.Forms.TextBox();
pt_entries[i].send = new System.Windows.Forms.Button();