Hi,

I have a windows form that adds new entries to a dataset via a datagrid using the updateAll method. Im passing in an id from another form and id like to specify this in the sata thats being written to the dataset. So by default the id would already be whatever has been passed to the form...

whats the best way to go about this?

Hope that makes sense!

Thanks

Dani AI

Generated

— you want every new row created in the grid to pick up an ID passed in from the other form. 's pointer about keys is useful for table design, but practically you usually want to set that incoming value as a default/initial value for new rows (a foreign key), not as the table's auto-increment primary key. Here are simple, proven ways to do that so TableAdapterManager.UpdateAll (or your Update call) writes the correct value.

Set the DataColumn default (easy, global for that DataTable):

private int _parentId;

public ChildForm(int parentId) {
    InitializeComponent();
    _parentId = parentId;
    dataSet.Tables["Child"].Columns["ParentId"].DefaultValue = _parentId;
}

Handle new-row creation on the DataTable (fires for all adds, including programmatic ones):

dataSet.Tables["Child"].TableNewRow += (s,e) => {
    e.Row["ParentId"] = _parentId;
};

For a WinForms DataGridView let the grid provide defaults when the user starts a row:

dataGridView1.DefaultValuesNeeded += (s,e) => {
    e.Row.Cells["ParentId"].Value = _parentId;
};

Or add rows yourself (explicit, safest):

var row = dataSet.Tables["Child"].NewRow();
row["ParentId"] = _parentId;
dataSet.Tables["Child"].Rows.Add(row);

Troubleshooting/cautions: don’t try to write into a column that’s an AutoIncrement identity in the DB — that’s for primary keys only. Make sure you set the value before calling Update/UpdateAll (and don’t call AcceptChanges before Update). If you need referential integrity, add a DataRelation between parent and child tables so constraints are checked in-memory.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.