开发者

Automatically setting foreign keys & autonumbers in new DataGridView rows?

I have an order table with the following columns:

orderid, clientid, [columns for order details] ...

I am then displaying this table, for a specific client, using a DataGridView. I have both the orderid and clientid columns hidden, however, as the orderid is a autonumbered primary key and the clientid is constant.

Unfortunately, when new rows are added to the DataGridView they are not persisted to the database. I believe this is because the orderid defaults to -1 and/or the clientid defaults to null whenever a new row is inserted into the DataGridView, but because those columns are hidden the user cannot change them.

So, my question:

How can I get the orderid to b开发者_StackOverflow社区e selected automatically and have the clientid default to the currently displayed client, whenever a new row is inserted?


It appears I can trap the UserAddedRow event and manually set the correct value there:

private void myDataGridView_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
    myDataGridView[clientidColumn.Index, e.Row.Index - 1].Value = clientid;
}

This now correctly persists the new orders to the database, although it seems a bit hacky (why must it be e.Row.Index - 1?). Is there not a way to specify the default values for columns on new rows?


You probably want to create a Master/Detail form

http://msdn.microsoft.com/en-us/library/y8c0cxey.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜