3
Answers

Updating SQL Server database DataRow problem

Florijan Vazal

Florijan Vazal

13y
1.9k
1
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;


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!
Answers (3)