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
You need to declare ds to something… try….
EDIT: Fixed code to add datatable to the dataset.
Also, be sure to initialize all variables, these look suspicious:
It looks as though these are declared in the class itself, put this outside of the function:
Also, I do not know what da is supposed to be, but you’ll need to instantiate that as well.