This is my code:
private string[] MesiSelezionati;
protected void Page_Load(object sender, EventArgs e)
{
MesiSelezionati = new string[] { "2", "4" };
UpdateMesi();
}
override protected void OnInit(EventArgs e)
{
for (int i = 1; i <= 12; i++)
{
HtmlGenericControl meseItem = new HtmlGenericControl("a") { InnerHtml = "mese" };
meseItem.Attributes.Add("href", "javascript:void(0);");
HiddenField hf = new HiddenField();
hf.Value = "0";
hf.ID = "idMese_" + i.ToString();
meseItem.Controls.Add(hf);
panelMesi.Controls.Add(meseItem);
}
base.OnInit(e);
}
private void UpdateMesi()
{
foreach (HtmlGenericControl a in panelMesi.Controls.OfType<HtmlGenericControl>())
{
HiddenField hf = a.Controls.OfType<HiddenField>().LastOrDefault();
if (MesiSelezionati.Contains(hf.ID.Split('_').LastOrDefault()))
{
hf.Value = "1";
a.Attributes.Add("class", "box-ricerca-avanzata-item link-box selected");
}
}
}
When I call the page, everything is fine! The problem is that I am invoking the same page (like postback) thanks to asp: LinkButton. I get a System.NullReferenceExceptionon if (MesiSelezionati.Contains(hf.ID.Split('_').LastOrDefault())).
It seems that the HiddenField lines 2 ° and 4 ° (which corresponds to position c MesiSelezionati = new string[] { "2", "4" };) is zero. What for? And how can I fix this?
EDIT: Code for Mark M
HtmlGenericControl optionBox = new HtmlGenericControl("div");
optionBox.Attributes["class"] = "option-box";
HtmlGenericControl optionBoxItem = new HtmlGenericControl("a") { InnerHtml = " " };
optionBoxItem.Attributes.Add("href", "javascript:void(0);");
optionBoxItem.Attributes.Add("class", "option-box-item");
HtmlGenericControl optionBoxTesto = new HtmlGenericControl("a") { InnerText = Categoria.Categoria };
optionBoxTesto.Attributes.Add("href", "javascript:void(0);");
optionBoxTesto.Attributes.Add("class", "option-box-testo");
HiddenField hf = new HiddenField();
hf.Value = "0";
hf.ID = "categoria_" + Categoria.UniqueID;
optionBox.Controls.Add(optionBoxItem);
optionBox.Controls.Add(optionBoxTesto);
optionBox.Controls.Add(hf);
panelCategorieGuida.Controls.Add(optionBox);
source
share