# 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();
}
}
}
您是否想插入一名员工?如果是这样,请替换您的 if 条件
使用
if(!string.IsNullorEmpty(textBox2.Text))
或者,您可以使用保护子句来使代码更简洁