HOWTO: Insert New Row

  • Thread starter Thread starter Greif
  • Start date Start date
G

Greif

I want to write a funciton that has 2 parameters(string
tableName and IDbDataParameter[] params). I can't seem to
figure out how to create a new record using a combination
of a Dataset/DataTable/DataRow. Or is there a better way to
insert rows?
 
Are you trying to populate a DataTable/DataSet with the
parameters from the method?

if so, has the table been created at the point you
describe below?

- Rob
 
Nothing has been created. This would be a static method to
insert a row via a disconnected db connection.
 
Hi Greif,
Rough written

A dataset without a primary key
dataset.table(0).rows.add(dataset.table(0).newrow)

With keys that has to be filled in advance, you first have to make a
datarow, fill the keys and than add the newrow

dr=dataset.table(0).newrow
dr("keyfield")=keyobject(0)
dataset.table(0).rows.add(dr)

I hope this helps a little bit?

Cor
 
The hard part of this was trying to keep it abstract. I had
to write some abstract functions to create the DataAdapter
and the InsertCommand (using the data provider's
commandbuilder). But it works. This is what I came up with.

public virtual int singleInsert2(string tableName, params
IDbDataParameter[] values)
{
if(ConnectionString == "" || ConnectionString.Length == 0)
throw new InvalidOperationException("The connection
string is not set. Set the 'ConnectionString' member.");

DataSet ds = new DataSet(tableName);
IDbDataAdapter dataAdapter = GetDataAdapter(tableName,
ConnectionString);
dataAdapter.InsertCommand = GetInsertCommand(dataAdapter);
dataAdapter.FillSchema(ds, SchemaType.Source);
DataRow newRow = ds.Tables["Table"].NewRow();

foreach(IDbDataParameter param in values)
{
newRow[param.ParameterName] = param.Value;
}

ds.Tables["Table"].Rows.Add(newRow);
return dataAdapter.Update(ds);
}
 
Back
Top