C# Retain PlaceHolder ViewState

T

theo

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);

}

}
}
 
S

SevDer

theo said:
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.
 
T

theo

Hi ....not 100% sure of your last sugesstions but I did some work on
restructuring the way I call the page functions to gernerate the
dynamic content...but I have landed back at the same point of not been
able to access the placeholders dropdownlists item content.Here is a
summary,the new error msg and code...many thanks Theo

Program flow...load file,then extract the xml text tags from the
file,then the number of
Xml tags retrieved from the file determines the number of dropdownlist
controls
instanciated in the placeholder,the user selects the required tags from
the
dropdownlists (if 5 Xml tags,then 5 dropdownlists each containing 5 xml
tags) and now
the btnSave button is selected which extracts the user selection form
the dropdownlists.

Once the btnLoadXmlTags_Click is selected,an array is filled with the
xml tags,this
function also creates a session variable call "OkToRecreateControls"
which permits Page
OnInit to recreate the controls for subsequent postbacks,then the
btnLoadXmlTags_Click function calls the CreateDynamicControls which in
turn calls
the function AddContentToDynamicControls.

All of the above works fine and for subsequent postbacks page onInit
calls
CreateDynamicControls which will now run since the
"OkToRecreateControls" session
variable is now valid.

Problem - when I try to extract the user selection form the
dropdownlists using the
using btnSave function the following error is generated...

Error Msg...

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of
the current web
request.
Please review the stack trace for more information about the error and
where it originated
in the code.

Exception Details: System.NullReferenceException: Object reference not
set to an instance
of an object.

Source Error:


Line 276: DropDownList ddl = new DropDownList();
Line 277: ddl.ID = DropDownListName;
Line 278: strSeletedItems+= ddl.SelectedItem.Text + "\\n";

Source File: e:\complexx\aspxmldbmapper_v2\wfrmmain4.aspx.cs Line:
270

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an
object.]
AspXmlDbMapper_v2.wfrmMain4.ReadDropDownLists() in
e:\complexx\aspxmldbmapper_v2\wfrmmain4.aspx.cs:270
AspXmlDbMapper_v2.wfrmMain4.btnSave_Click(Object sender, EventArgs
e) in e:\complexx\aspxmldbmapper_v2\wfrmmain4.aspx.cs:253
System.Web.UI.WebControls.Button.OnClick(EventArgs e)

System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String
eventArgument)
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler
sourceControl, String eventArgument)
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
System.Web.UI.Page.ProcessRequestMain()


Code sample...

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Xml;
using System.Data.SqlClient;
using System.Configuration;

namespace AspXmlDbMapper_v2
{

public class wfrmMain4 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.PlaceHolder plhDbContent;
protected System.Web.UI.WebControls.PlaceHolder plhXmlContent;
protected System.Web.UI.HtmlControls.HtmlInputFile fileDb;
protected System.Web.UI.HtmlControls.HtmlInputFile fileXml;

protected System.Web.UI.WebControls.Button btnLoadXml;
protected System.Web.UI.WebControls.Button btnLoadXmlTags;
protected System.Web.UI.WebControls.Button btnSave;
protected System.Web.UI.HtmlControls.HtmlGenericControl span2;
protected System.Web.UI.WebControls.DropDownList ddlXmlTagList;
protected System.Web.UI.LiteralControl literal;

private string xmlFileDestination = "";
private ArrayList aryTxtNodes = new ArrayList();
private ArrayList aryEleNodes = new ArrayList();
private ArrayList aryAtrbNodes = new ArrayList();

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

}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
CreateDynamicControls();
InitializeComponent();
base.OnInit(e);
}

private void InitializeComponent()
{
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 )
{
//error check...file has .xml extentsion
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...loaded 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:
//assign last element name tag and current text value to string
myNode = "<" + aryEleNodes[aryEleNodes.Count-1].ToString() + ">" +
xmlReader.Value;
aryTxtNodes.Add(myNode);
textCount++;
break;
}
}
streamreader.Close();
xmlReader.Close();
string strObj = "true";
Session["OkToRecreateControls"] = strObj;
Session["tempArray"] = aryTxtNodes;
CreateDynamicControls();
}
catch(Exception exc)
{
span2.InnerHtml = "Error...loading xml tags </b><br>"+ exc.ToString();
}
}

public void CreateDynamicControls()
{
string strOkToRecreateControls =
(string)Session["OkToRecreateControls"];

if (strOkToRecreateControls != null)
{
ArrayList aryNodes = (ArrayList)Session["tempArray"];

for (int createControl=0; createControl < aryNodes.Count;
createControl++)
{
literal = new LiteralControl();
literal.ID = "ltrId" + (createControl + 1).ToString();
plhXmlContent.Controls.Add(literal);


ddlXmlTagList = new DropDownList();
ddlXmlTagList.ID = "ddlId" + (createControl + 1).ToString();
plhXmlContent.Controls.Add(ddlXmlTagList);
}

string strObj = "true";
Session["OkToAddContent"] = strObj;
Session["OkToRecreateControls"] = strOkToRecreateControls;
AddContentToDynamicControls();
}
}

public void AddContentToDynamicControls()
{
string strOkToAddContent = (string)Session["OkToAddContent"];

if (strOkToAddContent != null)
{
ArrayList aryNodes = (ArrayList)Session["tempArray"];

for (int addContent = 0; addContent < aryNodes.Count; addContent++)
{
string ltrName = "ltrId" + (addContent + 1).ToString();
string ddlName = "ddlId" + (addContent + 1).ToString();

LiteralControl ltl =
(LiteralControl)this.FindControl("plhXmlContent").FindControl(ltrName);
DropDownList ddl =
(DropDownList)this.FindControl("plhXmlContent").FindControl(ddlName);

ltl.Text = "<p><strong>Xml Tag " + (addContent + 1) + ":</b>";

for(int addItem = 0;addItem < aryNodes.Count;addItem++)
{
ddl.Items.Add(aryNodes[addItem].ToString());
}

ddl.SelectedIndex = addContent;
}
}
}

private void btnSave_Click(object sender, System.EventArgs e)
{
MsgBox(ReadDropDownLists());
}

public string ReadDropDownLists()
{
string strSeletedItems = "";

for (int i = 0; i<Page.Controls.Count; i++)
{
string DropDownListName = "ddlXmlTagList" + (i+1).ToString();
DropDownList ddl =
(DropDownList)Page.FindControl("plhXmlContent").FindControl(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);
}
}
}


dynamically created controls
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top