0

I have the following code:

    protected void Page_Load(object sender, EventArgs e)
    {

        if(!Page.IsPostBack)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("PName");
            dt.Columns.Add("Rate");
            dt.Columns.Add("Qty");
            dt.Columns.Add("Amount");
            dt.AcceptChanges();
            ViewState["v1"] = dt;
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        DataTable dt2 = (DataTable)ViewState["vi"];
        string sPname = TextBox1.Text;
        string sRate = TextBox2.Text;
        string sQty = TextBox3.Text;
        double d1 = Convert.ToDouble(sRate)* Convert.ToDouble(sQty);

        DataRow dr = dt2.NewRow();
        dr[0] = sPname;
        dr[1] = sRate;
        dr[2] = sQty;
        dr[3] = d1.ToString("0.00");
        dt2.Rows.Add(dr);
        dt2.AcceptChanges();
        ViewState["v1"] = dt2;

        GridView1.DataSource = dt2;
        GridView1.DataBind();

Error Here:

DataRow dr = dt2.NewRow();
An exception of type 'System.NullReferenceException' occurred in Formsdata.dll but was not handled in user code

Additional information: Object reference not set to an instance of an object.

After inserting values and clicking on button. I'm using visual studio 2013, beginner!

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Suman Baul
  • 133
  • 1
  • 11
  • Whenever you ask about an exception, you must post the full exception, including the stack trace and inner exceptions. – John Saunders Sep 26 '14 at 20:56
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – John Saunders Sep 26 '14 at 21:01

1 Answers1

2

Your ViewState object from which you are getting the DataTable doesn't contain any DataTable.

The issue is that you are assigning the DataTable in a ViewState object which has the key v1 but you are accessing it from vi. So vi doesn't contain anything.

Try with this in the first line of your button click event handler code.

DataTable dt2 = (DataTable)ViewState["v1"];
Sachin
  • 40,216
  • 7
  • 90
  • 102