bobthemac
bobthemac

Reputation: 1172

c# data row error from tutorial

I have been following a tutorial on the internet it can be found at Add a New Record to the Database. I have code that is identical for input in to a dataset and database, but I get this error

Object reference not set to an instance of an object.

here is my full code

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        System.Data.SqlClient.SqlConnection con;
        System.Data.SqlClient.SqlDataAdapter da;
        DataSet ds1;


        int MaxRows = 0;
        int inc = 0;

        private void Form1_Load(object sender, EventArgs e)
        {
            con = new System.Data.SqlClient.SqlConnection();
            ds1 = new DataSet();

            con.ConnectionString = "Data Source=localhost;Initial Catalog=Kart_Setup;Integrated Security=True;Pooling=False";

            con.Open();

            da.Fill(ds1, "Setup");   
        }

        private void clr_Click(object sender, EventArgs e)
        {


        }

        private void save_Click(object sender, EventArgs e)
        {
            System.Data.SqlClient.SqlCommandBuilder cb;
            cb = new System.Data.SqlClient.SqlCommandBuilder(da);


          DataRow dRow = ds1.Tables["Setup"].NewRow();

          dRow[1] = FL.Value;
          dRow[2] = FR.Value;
          dRow[3] = RL.Value;
          dRow[4] = RR.Value;

          ds1.Tables["Setup"].Rows.Add(dRow);

          MaxRows = MaxRows + 1;
          inc = MaxRows - 1;

          da.Update(ds1, "Setup");

          MessageBox.Show("Setup Added");

          con.Close();
        }
    }
}

Any help would be appreciated thanks in advance

Upvotes: 0

Views: 630

Answers (2)

Jeffrey Kevin Pry
Jeffrey Kevin Pry

Reputation: 3296

You need to declare ds to something... try....

EDIT: Fixed code to add datatable to the dataset.

DataSet ds1 = new DataSet();
DataTable dt = new DataTable("Setup");
ds1.Tables.Add(dt);
DataRow dRow = ds1.Tables["Setup"].NewRow();

Also, be sure to initialize all variables, these look suspicious:

MaxRows = MaxRows + 1;
inc = MaxRows - 1;

It looks as though these are declared in the class itself, put this outside of the function:

public intMaxRows = 0;
public int inc = 0;

Also, I do not know what da is supposed to be, but you'll need to instantiate that as well.

Upvotes: 3

user1921
user1921

Reputation:

What is da? Is it null?

Have you initialized ds1?

Is FL null?

Is FR null?

Is RL null?

Is RR null?

What about MaxRows? inc?

You haven't provided enough information to get any real help.

EDIT:

Based on your comment, ds1 needs to be initialized.

Upvotes: 1

Related Questions