长话短说,我必须将数据从C#表单发送到SQL,但是我在这一行中不断获取Null引用:
adapter.InsertCommand.Parameters["@genre"].Value = textBox1.Text;
单击按钮将数据发送到数据库时出现错误。它还说:
引用未设置的对象”。
我尝试了一些方法来修复它,但似乎无法弄清楚空值在哪里。这是该表格的完整代码。请记住,如果有任何相关性,那么我在同一项目上有更多表格:
public partial class Form4 : Form
{
public Form4()
{
InitializeComponent();
}
private SqlConnection connection;
private SqlDataAdapter adapter;
private void Form2_Load(object sender, EventArgs e)
{
connection = new SqlConnection("Data Source=USER;Initial Catalog=administracion;Integrated Security=True");
adapter = new SqlDataAdapter();
SqlCommand save = new SqlCommand("insert into genres (genre, genre_description)"+
"values (@genre, @genre_description)", connection);
adapter.InsertCommand = save;
adapter.InsertCommand.Parameters.Add(new SqlParameter("@genre", SqlDbType.VarChar));
adapter.InsertCommand.Parameters.Add(new SqlParameter("@genre_description", SqlDbType.VarChar));
}
private void textBox_TextChanged(object sender, EventArgs e)
{
textBox1.MaxLength = 50;
textBox2.MaxLength = 200;
}
private void button1_Click(object sender, EventArgs e)
{
adapter.InsertCommand.Parameters["@genre"].Value = textBox1.Text; // on this line I get the null reference exception
adapter.InsertCommand.Parameters["@genre_description"].Value = textBox2.Text;
try
{
connection.Open();
adapter.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Genre added to database", "Data Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (SqlException exception)
{
MessageBox.Show(exception.ToString());
}
finally
{
connection.Close();
}
}
}
我是使用该特定编程语言的新手,因此,如果这是一个非常基本的问题,我想道歉(可能是)
查看代码,我怀疑您还没有启动load事件。由于该加载事件处理程序正在创建您的SQL连接,插入命令等,因此它们为null,因为未调用它,并且您正在按钮单击事件处理程序中对其进行访问。
为了证明理论改变了这一点:
public Form4()
{
InitializeComponent();
}
对此:
public Form4()
{
InitializeComponent();
this.Load += Form4_Load;
this.Closed += Form4_Closed;
}
添加此:
void Form4_Closed(object sender, EventArgs e)
{
this.Load -= Form4_Load;
this.Closed -= Form4_Closed;
}
并改变这个
private void Form2_Load(object sender, EventArgs e)
对此
private void Form4_Load(object sender, EventArgs e)
由于您的表单名为Form4,而不是Form2(我假设您是从项目中的另一个表单复制过来的?)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句