Suman Baul
Suman Baul

Reputation: 153

NullReferenceException in formsdata.dll

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!

Upvotes: 0

Views: 1423

Answers (1)

Sachin
Sachin

Reputation: 40970

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"];

Upvotes: 2

Related Questions