[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

Generate XML from hash table error

Posted on 2010-11-21
3
Medium Priority
?
1,057 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 2000 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

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…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…

649 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