Re: C# Retain PlaceHolder ViewState



theo wrote:
Hi...

I wish to extract the text content of an Xml file and assign it to
DropDownList controls at runtime.I can get the Xml file text content
into the DropDownList controls (Ex...if 5 Xml text tags then 5
dropdownlist controls each containing the 5 Xml text tags).

Problem,when I save the user DropDownList selected items by means of a
button click the web form looses the PlaceHolder viewstate and
generates the following error..."Object reference not set to an
instance of an object....strSeletedItems+= ddl.SelectedItem.Text +
"\\n";"

How do I retain the PlaceHolders viewstate?.....when I enable the
PlaceHolder's viewstate I get the this error..."The type
'System.Web.UI.WebControls.PlaceHolder' must be marked as Serializable
or have a TypeConverter other than ReferenceConverter to be put in
viewstate.
"

Code sample...


namespace AspXmlDbMapper_v2 {

public class wfrmMain : System.Web.UI.Page
{

private void Page_Load(object sender, System.EventArgs e)
{

}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{

InitializeComponent();
base.OnInit(e);
}


private void InitializeComponent() { this.btnLoadDb.Click += new System.EventHandler(this.btnLoadDb_Click); this.btnLoadXml.Click += new System.EventHandler(this.btnLoadXml_Click); this.btnLoadXmlTags.Click += new System.EventHandler(this.btnLoadXmlTags_Click); this.btnSave.Click += new System.EventHandler(this.btnSave_Click); this.Load += new System.EventHandler(this.Page_Load);

}
#endregion



private void btnLoadXml_Click(object sender, System.EventArgs e)
{

string fileDestination = "C:\\TempXml";
string fileName = Path.GetFileName(fileXml.Value);
string fileExtentsion = Path.GetExtension(fileXml.Value);

xmlFileDestination = Path.Combine(fileDestination,fileName);

Session["xmlFilePath"] = xmlFileDestination;

if (fileXml.PostedFile != null )
{
if (fileExtentsion.ToString().Equals(".xml"))
{
try
{
fileXml.PostedFile.SaveAs(xmlFileDestination);
span2.InnerHtml = "File uploaded successfully to <b>" +
xmlFileDestination + "</b>";
Session["xmlFileLoadedOk"] = true;
fileXml.Dispose();

}
catch (Exception exc)
{
span2.InnerHtml = "Error saving file <b>" + xmlFileDestination +
"</b><br>"+ exc.ToString();
}
}
else
{
MsgBox("Error incorrect file type  \\n\\nCorrect file type is \"
filename.xml \"");
}

}

}

private void btnLoadXmlTags_Click(object sender, System.EventArgs e)
{

int elementCount=0, attributeCount=0, textCount=0;

try
{
string fileDestination = (string)Session["xmlFilePath"];
StreamReader streamreader = new StreamReader (fileDestination);
XmlTextReader xmlReader = new XmlTextReader (streamreader);

while (xmlReader.Read())
{
string myNode = "";

switch (xmlReader.NodeType)
{
case XmlNodeType.Element:
elementCount++;
myNode = xmlReader.Name;
aryEleNodes.Add(myNode);

if (xmlReader.HasAttributes)
{
attributeCount++;
myNode = xmlReader.Value;
aryAtrbNodes.Add(myNode);
}
break;

case XmlNodeType.Text:
textCount++;
myNode = "<" + aryEleNodes[aryEleNodes.Count-1].ToString() + ">" +
xmlReader.Value;
aryTxtNodes.Add(myNode);
break;

}
}

CreateXmlDropDownLists();
}

catch(Exception ecpt)
{
span2.InnerHtml = "Error...loading xml tags </b><br>"+ ecpt.ToString();
}

}


public void CreateXmlDropDownLists() {

int intCounter;

for (intCounter=0; intCounter < aryTxtNodes.Count; intCounter++)
{
AddXmlDropDownList(aryTxtNodes,intCounter);
}

Session["PlaceHolderControlCount"] = plhXmlContent.Controls.Count;
//plhXmlContent.EnableViewState = true;
//ViewState["plhXmlContent"] = plhXmlContent;

}

public void AddXmlDropDownList(ArrayList aryTxtNodes,int nodePos)
{

int nodeNumber =   nodePos + 1;
literal = new LiteralControl();
plhXmlContent.Controls.Add(literal);
literal.Text = "<p><strong>Xml Tag " + nodeNumber + ":</b>";

ddlXmlTagList = new DropDownList();
plhXmlContent.Controls.Add(ddlXmlTagList);
ddlXmlTagList.ID = "ddlXmlTagList" + nodeNumber;
ddlXmlTagList.EnableViewState = true;

//add xml tag content  to ddl
for(int a = 0;a < aryTxtNodes.Count;a++)
{
ddlXmlTagList.Items.Add(aryTxtNodes[a].ToString());
}

ddlXmlTagList.SelectedIndex = nodeNumber - 1;

}

private void btnSave_Click(object sender, System.EventArgs e)
{

//using this for debugging,but throws error "Object
//reference not set to an instance of an  object.
//...strSeletedItems+= ddl.SelectedItem.Text + "\\n";"
MsgBox(ReadDropDownLists());

}
public string ReadDropDownLists()

{
string strSeletedItems = "";
//int n = (int)Page.FindControl("plhXmlContent").Controls.Count;
int n = (int) Session["PlaceHolderControlCount"];

for (int i = 0; i<n; i++)
{
string DropDownListName = "ddlXmlTagList" + (i+1).ToString();
//DropDownList ddl =
(DropDownList)Page.FindControl("plhXmlContent").FindControl(DropDownListName);
DropDownList ddl = new DropDownList();
ddl.ID =  DropDownListName;
strSeletedItems+= ddl.SelectedItem.Text + "\\n";
}

return strSeletedItems;

}

public void MsgBox(string strMsg)
{

string alertScript;

alertScript = "<script language=JavaScript> alert('" + strMsg +"');
</script" +">";

if (!IsClientScriptBlockRegistered("alert"))
this.RegisterClientScriptBlock("alert", alertScript);


}
}
}


The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request. ---> System.Web.HttpException: Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.


--

SevDer
http://www.sevder.com
.