Reputation: 23
I'm trying to update the database using a method were the parameters of the method will be used rather then using an SQL statement. I did this so a user can enter information into the database.
System.Data.OleDb.OleDbConnection con;
DataSet dsl;
System.Data.OleDb.OleDbDataAdapter da;
public String updateDatabase(int id, String Fname, String Lname, int age, string job)
{
con = new System.Data.OleDb.OleDbConnection();
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\Owner\\Documents\\CIS3052.mdb";
dsl = new DataSet();
da = new System.Data.OleDb.OleDbDataAdapter();
con.Open();
DataRow dRow = dsl.Tables["Employee"].NewRow();
dRow["ID"] = id;
dRow["Fname"] = Fname;
dRow["Lname"] = Lname;
dRow["Age"] = age;
dRow["Job"] = job;
dsl.Tables["Employee"].Rows.Add(dRow);
da.Update(dsl, "Employee");
return null;
}
The problem I have is in this line:
DataRow dRow = dsl.Tables["Employee"].NewRow();
It is telling me:
Object reference not set to an instance of an object.
I tried using da.Fill()
but I cannot find a way to use that without using a SQL statement.
Thanks.
Upvotes: 1
Views: 1681
Reputation: 66389
You must first fill the dataset.
Untested, but worth trying:
con.Open();
da = new System.Data.OleDb.OleDbDataAdapter();
da.SelectCommand = new OleDbCommand("Employee", con);
da.SelectCommand.CommandType = CommandType.TableDirect;
da.Fill(dsl);
Choosing CommandType.TableDirect
should bring you the whole table without using whole SQL statement.
Upvotes: 0
Reputation: 1784
Because dsl.Tables["Employee"]
dose not exist. Once you fill dsl.Tables["Employee"]
with da.Fill()
then it become available.
Once you called
DataRow dRow = dsl.Tables["Employee"].NewRow();
You are trying to access the "Employee" table in dataset, but dataset does not know about Employee
table until you tell it (by calling da.Fill()
).
IMO there is no way to call DataRow dRow = dsl.Tables["Employee"].NewRow();
without filling it.
Upvotes: 1
Reputation: 1975
This is becuase you don´t have any table called Employee in you dataset. This is a very complicated to update record in a database. You might try the SQLCommand class instead
string sql= "Build you query";
using (SqlConnection connection = new SqlConnection(
"your connectionstring"))
{
SqlCommand command = new SqlCommand(
sql, connection);
connection.Open();
command.ExecuteNonQuery();
reader.Close();
}
Upvotes: 0
Reputation: 824
It is because there is nothing in your dataset. Check your code there.
Upvotes: 1