# System.NullReferenceException:“未将对象引用设置为对象的实例。”

问题描述 投票:0回答:1

# System.NullReferenceException:“未将对象引用设置为对象的实例。”

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();
        }
    }
}

我在这段代码中遇到了这个错误。请尽快帮助任何人请提供解决方案。一切都很好,但我面临着“dc.SubmitChanes”中的问题

c# linq-to-sql
1个回答
0
投票

您是否想插入一名员工?如果是这样,请替换您的 if 条件

使用

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

或者,您可以使用保护子句来使代码更简洁

© www.soinside.com 2019 - 2024. All rights reserved.