views:

56

answers:

1

I am trying to bind a table in an SQL database to a DataGridView Control. I would like to make it so that when the user enters a new line of data in the DataGridView that a record is automatically added to the database. Here is my current attempt...

    BOMClassesDataContext DB = new BOMClassesDataContext();

    Form_Load()
    {
        var mfrs = from m in DB.Manufacturers
                   select m;

        BindingSource bs = new BindingSource();
        bs.DataSource = mfrs;

        dataGridView1.DataSource = bs;
    }

    dataGridView_CellValueChanged()
    {
        try
        {
            DB.SubmitChanges()
        }
        catch(Exception Ex)
        {
            MessageBox.Show(Ex.Message);
        }
    }

If I click the bottom empty row it automatically fills in the ID (identity) column of the table with a "0" instead of the next unused value. If I change that value manually to the next available then it adds the new record fine but if I leave it at 0 it does nothing. How can i fix this? In my LINQ to SQL classes the ID column of the table has the AutoGenerate property set to true.

+1  A: 

You need to execute DB.SubmitChanges() when the user has finished.

With Linq To SQL, no changes are made to the underlying database until you do that.

Blorgbeard
Ok, that works as long as I enter the ID (identity column) in manually. Is there a way to get it to automatically increment the ID column? The ID column is setup as an Identity.
Jordan S
Also on what event is it best to use to fire the SubmitChanges method? CellValueChanged?
Jordan S
@Jordan: In your Linq-To-Sql designer, change the ID column's "Auto Generated Property" value to True. Hide it from the data grid unless there is a reason for the users to see it.
magnifico
@Jordan: You should update your question to include your follow up questions, or you should ask new questions to address the follow up questions.
magnifico
@magnifico, can you give me a little more info how to do that??
Jordan S
@Jordan: http://geekswithblogs.net/AzamSharp/archive/2008/03/13/120517.aspx
magnifico