本文介绍了更新SQL Server数据库n C#DataRow问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好.
我正在尝试向数据库添加一行.
这是我一直在使用的代码:
Hello everyone.
I am trying to add a row to my database.
This is the code i have been using:
public bool Insertdata(string Name, string LastName, string Sex) {
System.Data.SqlClient.SqlConnection con;
System.Data.SqlClient.SqlDataAdapter adapter1;
DataSet dset1;
con = new System.Data.SqlClient.SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=c:\\documents and settings\\korisnik\\my documents\\visual studio 2010\\Projects\\WindowsFormsApplication2\\WindowsFormsApplication2\\Database1.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
dset1 = new DataSet();
adapter1 = new System.Data.SqlClient.SqlDataAdapter("SELECT * FROM ljudi", con);
System.Data.SqlClient.SqlCommandBuilder cb;
cb = new System.Data.SqlClient.SqlCommandBuilder(adapter1);
con.Open();
con.Close();
DataRow dRow = dset1.Tables["ljudi"].NewRow();
dRow[1] = Name;
dRow[2] = LastName;
dRow[3] = Sex;
dset1.Tables["ljudi"].Rows.Add(dRow);
adapter1.Update(dset1, "ljudi");
MessageBox.Show("Added");
return true;
现在,当我编译时,一切正常,但是当我运行程序并尝试添加数据时,出现以下错误:
对象引用未设置为对象的实例.
这发生在行DataRow dRow = dset1.Tables ["ljudi"].NewRow();
由于某种原因,我无法创建该DataRow
有什么建议吗?
谢谢!
Now, when i compile, everything goes OK, but when i run the program and try to add the data i get the following error:
Object reference not set to an instance of an object.
This happens on the line DataRow dRow = dset1.Tables["ljudi"].NewRow();
For some reason i can''t create that DataRow
Any suggestions?
Thank You!
推荐答案
con.Open();
adapter1.Fill(dset1);
con.Close();
或以其他方式读取数据.
or reading the data in some other way.
这篇关于更新SQL Server数据库n C#DataRow问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!