c# 未将对象引用设置到对象的实例
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace News
{
public partial class Add : Form
{
public Add()
{
InitializeComponent();
}
private void save_Click(object sender, EventArgs e)
{
//获取要插入数据库的每个字段的值
string Name = textName.Text; //姓名
string Sex = textSex.Text; //性别
//构建插入的SQL语句
string sql = string.Format("insert into news (Name,Sex) values('{0}','{1}')",Name,textSex);
if (textName.Text.Trim()=="" || textSex.Text.Trim()=="")
{
MessageBox.Show("请您填写完整的信息!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
else
{
try
{
//创建Command对象
SqlCommand command = new SqlCommand(sql, DBHelper.connection);
DBHelper.connection.Open(); //代开数据库连接
int result = command.ExecuteNonQuery(); //执行命令
//根据操作结果给出提示信息
if (result != 1)
{
MessageBox.Show("添加失败!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
MessageBox.Show("添加成功!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show("操作数据库出错!","操作提示",MessageBoxButtons.OK,MessageBoxIcon.Error);
Console.WriteLine(ex.Message);
}
finally
{
DBHelper.connection.Close(); 未将对象引用设置到对象的实例
}
this.Close();
}
}
private void exit_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
红字体报错