# System.NullReferenceException: 'Object reference not set to an instance of an object.'

217 Views Asked by At
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CURD_operation
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            CompanyDBDataContext dc = new CompanyDBDataContext();
            Employee obj = new Employee();
            if(obj.e_id!= null ||obj.e_name!=null ||obj.job!=null || obj.salary!=null ||obj.d_name!=null)
            {
                obj.e_id = int.Parse(textBox1.Text);
                obj.e_name = textBox2.Text;
                obj.job = textBox3.Text;
                obj.salary = long.Parse(textBox4.Text);
                obj.d_name = textBox5.Text;

                dc.Employees.InsertOnSubmit(obj); //pending insert state
                dc.SubmitChanges();
                MessageBox.Show("Record inserted in table.");
            }
            else
            {
                MessageBox.Show("Object is Null.");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            foreach (Control ctrl in Controls)
            {
                if(ctrl is TextBox)
                {
                    TextBox tb = ctrl as TextBox;
                    tb.Clear();
                }
            }
            textBox1.Focus();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

I get this error from the above code:

System.NullReferenceException: 'Object reference not set to an instance of an object.

Please help as soon as possible, please anyone give the solution. Everything is ok but I am facing this issue in dc.SubmitChanges

1

There are 1 best solutions below

0
Hilal On

are you trying to insert an employee? if so, replace your if conditions

use

if(!string.IsNullorEmpty(textBox2.Text))

alternatively, you can use guard clauses for much cleaner code