更新SQL Server数据库n C#DataRow问题 [英] Updating SQL server database n C# DataRow problem

查看:100
本文介绍了更新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!

推荐答案

如果发布的代码正确无误,请打开SqlConnection(con),然后立即将其关闭而不进行任何操作.

您可能会考虑做类似
的事情
If the code you have posted is accurate you open your SqlConnection (con) and then immediately close it again without doing anything with it.

You might consider doing something like
con.Open();
adapter1.Fill(dset1);
con.Close();



或以其他方式读取数据.



or reading the data in some other way.


这篇关于更新SQL Server数据库n C#DataRow问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆