0

I'm programming my first c# application, which has to connect to database. I want to save data from TextBoxes to database, but I have problem in marked line.

Code for connecting to database:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace prviTelefonskiImenik
{
    class DatabaseConnection
    {
        private string sql_string;
        private string strCon;
        System.Data.SqlClient.SqlDataAdapter da_1;

        public string Sql
        {
            set { sql_string = value; }
        }

        public string connection_string
        {
            set { strCon = value; }
        }

        public System.Data.DataSet GetConnection
        {
            get 
            { return MyDataSet(); }
        }

        private System.Data.DataSet MyDataSet()
        {
            System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(strCon);

            con.Open();

            da_1 = new System.Data.SqlClient.SqlDataAdapter(sql_string, con);

            System.Data.DataSet dat_set = new System.Data.DataSet();
            da_1.Fill(dat_set, "Table_Data_1");
            //da_1.Fill(dat_set, "kontakti");
            con.Close();

            return dat_set;
        }

        public void UpdateDatabase(System.Data.DataSet ds)
        {
            System.Data.SqlClient.SqlCommandBuilder cb = new System.Data.SqlClient.SqlCommandBuilder(da_1);
            cb.DataAdapter.Update(ds.Tables[0]);
        }
    }
}

And code for saving data from TextBoxes to database:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace prviTelefonskiImenik
{
    public partial class dodajKontakt : Form
    {
        public dodajKontakt()
        {
            InitializeComponent();
        }

        DatabaseConnection objConnect;
        string conString;

        DataSet ds;
        DataRow dRow;

        int MaxRows;
        int inc = 0;

        private void dodajKontakt_Load(object sender, EventArgs e)
        {
            try
            {
                objConnect = new DatabaseConnection();
                conString = Properties.Settings.Default.kontaktiConnectionString;

                objConnect.connection_string = conString;
                objConnect.Sql = Properties.Settings.Default.SQL;

                ds = objConnect.GetConnection;
                MaxRows = ds.Tables[0].Rows.Count;

                NavigateRecords();
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }

        private void NavigateRecords()
        {
            dRow = ds.Tables[0].Rows[inc];
            txtIme.Text = dRow.ItemArray.GetValue(1).ToString();
            txtPriimek.Text = dRow.ItemArray.GetValue(2).ToString();
            txtEmso.Text = dRow.ItemArray.GetValue(3).ToString();
            txtTelefon.Text = dRow.ItemArray.GetValue(4).ToString();
            txtEmail.Text = dRow.ItemArray.GetValue(5).ToString();
        }

        private void shrani_Click(object sender, EventArgs e)
        {

            **DataRow row = ds.Tables[0].NewRow();**
            row[1] = txtIme.Text;
            row[2] = txtPriimek.Text;
            row[3] = txtEmso.Text;
            row[4] = txtTelefon.Text;
            row[5] = txtEmail.Text;

            ds.Tables[0].Rows.Add(row);

            try
            {
                objConnect.UpdateDatabase(ds);
                MaxRows = MaxRows + 1;
                inc = MaxRows - 1;
                MessageBox.Show("Database updated");
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }
    }
}

While compiling, Visual Studio 2013 finds an error here: DataRow row = ds.Tables[0].NewRow(); Additional information: Object reference not set to an instance of an object.

Could you please help me to solve a problem? Thanks!

gradencan
  • 33
  • 1
  • 7
  • 1
    It doesn't find that error when compiling; that's a runtime error. The error is caused by either `ds` or `ds.Tables[0]` being `null` - most likely the former (since `Tables` is unlikely to include a `null` element). Are you calling this code before you've called `dodajKontakt_Load`? – Dan Puzey Aug 06 '14 at 10:16
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Daniel Kelley Aug 06 '14 at 10:17

2 Answers2

0

Check that ds.Tables is not null when this code invokes

0

You are facing this problem because your dataset has no table object, and you are doing change on it these why you get error of object reference

Check Count before applying change on it

if(ds!= null && ds.Tables.Count> 0)
{
DataRow row = ds.Tables[0].NewRow();
}
Sid
  • 801
  • 8
  • 19
  • Also doesn't work with this code: 1. length is underlined 2. If I make IF statement, all "row" become underlined. – gradencan Aug 06 '14 at 10:34
  • Now, I got error in try: **objConnect.UpdateDatabase(ds);** Additional information: Object reference not set to an instance of an object. – gradencan Aug 06 '14 at 11:29
  • Can you please give some details about your database and also what you are getting in ds in this row objConnect.UpdateDatabase(ds) – Sid Aug 06 '14 at 11:38
  • Database is normally created in project. There, I want to actually write to database, what is stored in table. – gradencan Aug 06 '14 at 11:41
  • You had created table in your database and there all columns are nullable or not? if not then also you will get this error if that mapped column in your table is null – Sid Aug 06 '14 at 11:47
  • Definition of database: `CREATE TABLE [dbo].[kontakti] ( [Id] INT IDENTITY (1, 1) NOT NULL, [ime] NCHAR (50) NULL, [priimek] NCHAR (50) NULL, [emso] NCHAR (50) NULL, [telefon] NCHAR (50) NULL, [email] NCHAR (50) NULL, PRIMARY KEY CLUSTERED ([Id] ASC) );` – gradencan Aug 06 '14 at 11:52
  • Add this line ds.Tables[0].AcceptChanges(); after ds.Tables[0].Rows.Add(row); and check again – Sid Aug 06 '14 at 11:55