Solved

Generate XML from hash table error

Posted on 2010-11-21
3
1,028 Views
Last Modified: 2013-11-11
I am facing a problem.

I have a grid where the selected values are trasposed to a hash table in c#

Server Error in '/XGISAustralia' Application.
--------------------------------------------------------------------------------

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 124:                    dataTable.Rows.Add(dataRow);
Line 125:                    //Code to generate XML
Line 126:                    XElement prod = XElement.Parse(string.Format(xml, hashtable["Product_ID"].ToString(), "", hashtable["ProductName"].ToString(), hashtable["ProductDesc"].ToString(), hashtable["ProductPrice"].ToString()));
Line 127://                    XElement prod = XElement.Parse(string.Format(xml, hashtable["Product_ID"].ToString(), "", hashtable["ProductName"].ToString(), hashtable["ProductDesc"].ToString(), hashtable["Qty"].ToString(), hashtable["Currency"].ToString(), hashtable["ProductPrice"].ToString()));
Line 128:                    Orders.Add(prod);
 

Source File: e:\Projects\Development\XGISAustralia\Applications\xPaypal\Controls\xt_PaymentSelector.ascx.cs    Line: 126

Stack Trace:


[NullReferenceException: Object reference not set to an instance of an object.]
   Applications_xTrain_Controls_xt_PaymentSelector.Button1_Click(Object sender, EventArgs e) in e:\Projects\Development\XGISAustralia\Applications\xPaypal\Controls\xt_PaymentSelector.ascx.cs:126
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +118
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563

 


--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1


And here is the code::

XHTML

<telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server" LoadingPanelID="RadAjaxLoadingPanel1"
    SkinID="Black" Width="645px">
    <telerik:RadGrid ID="RadGrid1" runat="server" Skin="Black" Width="640px" GridLines="None"
        DataSourceID="SqlDataSource2" AutoGenerateColumns="False" EnableLinqExpressions="False"
        BackColor="Transparent" AllowMultiRowSelection="True" OnItemCommand="RadGrid1_ItemCommand">
        <MasterTableView Summary="Video Lessons" ShowGroupFooter="false" AllowMultiColumnSorting="true"
            DataSourceID="SqlDataSource2" DataKeyNames="Product_ID">
            <CommandItemSettings ExportToPdfText="Export to Pdf" />
            <Columns>
                <telerik:GridTemplateColumn>
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" />
                    </ItemTemplate>
                </telerik:GridTemplateColumn>
                <telerik:GridTemplateColumn HeaderText="" SortExpression="XTV7_Categories_Image"
                    UniqueName=" XTV7_Categories_Image">
                    <ItemTemplate>
                        <asp:ImageButton ID="btnImageDisplay" runat="server" CommandName="Select" ImageUrl='<%# "~/App_Portal/xTrain/Images/CategoryLogos/" + Eval(" XTV7_Categories_Image") %>'
                            Width="100px" />
                    </ItemTemplate>
                </telerik:GridTemplateColumn>
                <telerik:GridBoundColumn DataField="ProductName" HeaderText="Product Name"
                    SortExpression="ProductName" UniqueName="ProductName" Visible="true">
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="ProductDesc" HeaderText="Overview" SortExpression="ProductDesc"
                    UniqueName="ProductDesc" Visible="true">
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="VidCount" HeaderText="VidCount" SortExpression="VidCount"
                    UniqueName="VidCount" Visible="true" ReadOnly="true">
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="ProductPrice" HeaderText="Cost" SortExpression="ProductPrice"
                    UniqueName="ProductPrice" Visible="true">
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="Product_ID" DataType="System.Int32" HeaderText="Product #"
                    SortExpression="Product_ID" UniqueName="Product_ID" Visible="false">
                </telerik:GridBoundColumn>
            </Columns>
        </MasterTableView>
        <ClientSettings>
            <Selecting AllowRowSelect="True" />
        </ClientSettings>
    </telerik:RadGrid>
    <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="ClientClick();"
        OnClick="Button1_Click" />
</telerik:RadAjaxPanel>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:XtrainConnectionString %>"
    
    SelectCommand="SELECT TOP (100) PERCENT XTV7_Categories_ID AS Product_ID, XTV7_Categories_Name AS ProductName, Overview AS ProductDesc, Videos AS VidCount, Cost AS ProductPrice, XTV7_Categories_Image FROM vw_xt_ddl_categories">
</asp:SqlDataSource>

Open in new window


C#

    protected void Button1_Click(object sender, EventArgs e)
    {
        foreach (GridDataItem item in RadGrid1.MasterTableView.Items)
        {
            CheckBox chk = (CheckBox)item.FindControl("CheckBox1");
            if (chk.Checked)
            {
                if (!File.Exists(Server.MapPath("~/App_Data/XML") + "\\Orders.xml"))
                {

                    XmlTextWriter textWritter = new XmlTextWriter(Server.MapPath("~/App_Data/XML") + "\\cart.xml", null);
                    textWritter.WriteStartDocument();
                    textWritter.WriteStartElement("Orders");
                    textWritter.WriteEndElement();

                    textWritter.Close();
                }

                //XDocument Orders = new XDocument();
                XElement Orders = new XElement("Orders");
                string xml = @"<OrderItems ProductID=""{0}"" ProductName=""{1}"" ProductDesc=""{2}"" ProductPrice=""{3}""/>";
//                string xml = @"<OrderItems ProductID=""{0}"" OrderID=""{1}"" ProductName=""{2}"" ProductDesc=""{3}"" Qty=""{4}"" Currency=""{5}"" ProductPrice=""{6}""/>";

                var dataTable = new DataTable("Cart_Items");

                dataTable.Columns.Add("Product_ID");
                dataTable.Columns.Add("ProductName");
                dataTable.Columns.Add("ProductDesc");
                //dataTable.Columns.Add("Qty");
               // dataTable.Columns.Add("Currency");
                dataTable.Columns.Add("ProductPrice");


                foreach (GridDataItem gridDataItem in RadGrid1.SelectedItems)
                {
                    var hashtable = new Hashtable();
                    gridDataItem.ExtractValues(hashtable);

                    DataRow dataRow = dataTable.NewRow();
                    foreach (DictionaryEntry entry in hashtable)
                    {
                        dataRow[entry.Key.ToString()] = entry.Value;
                    }
                    dataTable.Rows.Add(dataRow);
                    //Code to generate XML
                    XElement prod = XElement.Parse(string.Format(xml, hashtable["Product_ID"].ToString(), "", hashtable["ProductName"].ToString(), hashtable["ProductDesc"].ToString(), hashtable["ProductPrice"].ToString()));
//                    XElement prod = XElement.Parse(string.Format(xml, hashtable["Product_ID"].ToString(), "", hashtable["ProductName"].ToString(), hashtable["ProductDesc"].ToString(), hashtable["Qty"].ToString(), hashtable["Currency"].ToString(), hashtable["ProductPrice"].ToString()));
                    Orders.Add(prod);
                }
                Orders.Save(Server.MapPath("~/App_Data/XML") + "\\Orders.xml");
            }
        }
    }

Open in new window



the error is in the following line::

 XElement prod = XElement.Parse(string.Format(xml, hashtable["Product_ID"].ToString(), "", hashtable["ProductName"].ToString(), hashtable["ProductDesc"].ToString(), hashtable["ProductPrice"].ToString()));

Open in new window

0
Comment
Question by:XGIS
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 17

Accepted Solution

by:
sweetfa2 earned 500 total points
ID: 34185819
I am guessing that your hashtable does not contain some or all of the keys you require, so the ToString method is attempting to execute on a null object which is why you are getting the null reference.

Try checking that the hash["yourkey"] objects are not null before doing the error line.
0
 
LVL 7

Author Comment

by:XGIS
ID: 34186175
will do
0
 
LVL 7

Author Closing Comment

by:XGIS
ID: 34187766
Thanks, the grid was not passing two columns...
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

733 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question