[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1066
  • Last Modified:

Generate XML from hash table error

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
XGIS
Asked:
XGIS
  • 2
1 Solution
 
sweetfa2Commented:
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
 
XGISAuthor Commented:
will do
0
 
XGISAuthor Commented:
Thanks, the grid was not passing two columns...
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now