Solved

Generate XML from hash table error

Posted on 2010-11-21
3
1,007 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
  • 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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

757 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now