C# – Object reference not set to an instance of an object

c++

Hai,

In my code while executing a function i got regularly the exception error as "Object reference not set to an instance of an object"

The function exceuting is as follows

private void PageHeaderSetting(Graphics g)
        {
            try
            {
                DataTable dtPageHeader=new DataTable() ;
                dtPageHeader = ds.Tables["Page Header"];
                if (dtPageHeader.Rows.Count != 0)
                {
                    foreach (DataRow dr in dtPageHeader.Rows)
                    {
                        if (dr.ItemArray[0].ToString() != "")
                            PageHeaderText = dr.ItemArray[0].ToString();
                        else
                            PageHeaderText = "";
                        if (dr.ItemArray[1].ToString() != "")
                            PageHeaderFont = (Font)dr.ItemArray[1];
                        else
                            PageHeaderFont = new Font("Tahoma", 18, FontStyle.Bold, GraphicsUnit.Point);
                        if (dr.ItemArray[2].ToString() != "")
                            PageHeaderFormat = AlignmentSetting(dr.ItemArray[2].ToString());
                        else
                            PageHeaderFormat = AlignmentSetting(Convert.ToString(Alignment.Left));
                        if (dr.ItemArray[3].ToString() != "")
                            PageHeaderColor = (System.Drawing.Color)dr.ItemArray[3];
                        else
                            PageHeaderColor = Color.Black;

                        PageFooterText = Word_Wrap(PageHeaderText, PageHeaderFont, g, 0);
                        PageHeader(g);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

How can i solve this.Can anybody help me?

From the second line i got the exception error
means after declaring the datatable and putting the ds.Tables in it from there erroe occurs

Best Solution

This exception means you're trying to call a method on a null object. The exception should have given you a stack trace with the line number it was thrown at; this'll help you pin it down a bit. You could also try debugging it in visual studio and see where the exception is thrown & see what is null.