I am trying to develop a program that calculates the average grade of a semester with Windows Forms Application. Well, first I have a combobox and a button for deciding the number of lesson I take at that semester. When I select the number of lesson and click the button, it creates the amount of textbox(es) I want. There is nothing to worry about at this part. http://www.imageupload.co.uk/images/2015/01/26/Ads%C4%B1z.png http://www.imageupload.co.uk/images/2015/01/26/Ads%C4%B1z1.jpg
The problem that bugs me is the deletion of the dynamical contents. I think deleting and re-creating contents dynamically is a well idea for changing the amount of lesson more than once. This is my code for my solution.
public partial class Form1 : Form
{
int Syc = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
for (int k = 1; k <= 15; k++) {
comboBox1.Items.Add(k);
}
}
private void button1_Click(object sender, EventArgs e)
{
int En = 50;
int Item=Convert.ToInt32(comboBox1.SelectedItem);
TextBox[] d1 = new TextBox[Item];
ComboBox[,] d2 = new ComboBox[Item,2]; //Planning to use it afterwards
if (Syc == 1) Sil(d1); // Controls if the combobox changed before
Syc = 1;
for (int k = 0; k < Item; k++) {
d1[k] = new TextBox();
d1[k].Name = "textBox" + (k+1).ToString();
d1[k].Location = new Point(10,En);
d1[k].Size = new System.Drawing.Size(100, 15);
d1[k].Text = "";
this.Controls.Add(d1[k]);
En += 25;
}
}
private void Sil(TextBox[] d1) { //This part should have deleted
//the dynamical content that created before
for (int k = d1.Length-1; k >=0; k--) {
this.Controls.Remove(d1[k]);
d1[k].Dispose();
}
}
}
Well, I get a NullReferenceError at the line where d1[k].Dispose exists in Sil function. I feel really confused because there shouldn't be any reason for this kind of error. I created the instances of the textbox(es) and I even tried this again in Sil function. What do I miss here or what kind of solution would you suggest?