简体   繁体   中英

Linq to Entity insert data in db

How can I insert data added in GridView after clicking Save buton on BidingNavigator using Linq to Entity.

I am trying to add data to database but some problem occurs. I'm showing data using this code:

...

 private void PostojeciPRojekti_Load(object sender, EventArgs e)
        {

            dbcontext = new logicrms2Entities1();

            var projekti = from c in dbcontext.projekti
                             select c;

            projektiBindingSource.DataSource = projekti.ToList();
            projektiGridControl.Refresh();



        }

...

EDIT

I have try to save data using:

   private void projektiBindingNavigatorSaveItem_Click(object sender, EventArgs e)
    {


        dbcontext.SaveChanges();
        gridView1.RefreshData();


    }

First maintain a list of newly added objects in your form:

private List<projekti> addedList = new List<projekti>();

Then, handle RowsAdded event on your DataGridView:

dataGridView1.RowsAdded += new DataGridViewRowsAddedEventHandler(dataGridView1_RowsAdded);

Next, add any added object to the list in your RowsAdded event handler :

private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
     addedList.Add(dataGridView1.Rows[e.RowIndex].DataBoundItem as projekti);
}

Finally, in your navigator's save button click event handler method you can store the objects:

private void saveButton_Click(object sender, EventArgs e)
{
     var dbcontext = new logicrms2Entities1();
     addedList.ForEach(p=> dbcontext.projeckit.Add(p));
     dbcontext.SaveChanges()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM