hello every one
i will fill a 2D panel dynmically.
i have tried but i receive this error: Object reference not set to an instance of an object.
i have initialized the controls as following and try to fill the panel:
row=0, col=0;
HtmlForm form2 = new HtmlForm();
Panel[,] panelAd = new Panel[mm, 3];
Table mytable = new Table();
...
mytable.Controls.Add(trow_7);
if (col < 3)
{
panelAd[row, col].Controls.Add(mytable);
this.form2.Controls.Add(panelAd[row, col]);
}
else
{
row++;
col = 0;
panelAd[row, col].Controls.Add(mytable);
this.form2.Controls.Add(panelAd[row, col]);
}
how should i fix the error? on panelAd[row, col].Controls.Add(mytable); in if statement.
appreciate your respond with codes, kind regards

Amit MohantyRank #112 · 20K reputationPosted Aug 19, 2024, 1:24 AM EDT
I think the error occurs because the Panel[,] panelAd array is created, but each individual Panel object inside that array is not initialized before you attempt to use it. Try the below code once:
int row = 0, col = 0; HtmlForm form2 = new HtmlForm(); Panel[,] panelAd = new Panel[mm, 3]; Table mytable = new Table(); for (int i = 0; i < mm; i++) { for (int j = 0; j < 3; j++) { panelAd[i, j] = new Panel(); // This initializes each panel } } mytable.Controls.Add(trow_7); if (col < 3) { panelAd[row, col].Controls.Add(mytable); this.form2.Controls.Add(panelAd[row, col]); col++; } else { row++; col = 0; panelAd[row, col].Controls.Add(mytable); this.form2.Controls.Add(panelAd[row, col]); }