Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a very simple windows form project with Entity Framework.

Simply I draged my tables from "Data Source" tab in my "form" and it generate for me a "DataGridView" and a "BindingSource".

Data bound successfully and when I run project I can see "DataGridView" filled with data correctly and I can update any cells value from "DataGridView".

Problem is I can not insert any rows in my "DataGridView".

Here is some codes that I wrote hope it be useful to solve problem:

    Teachers_DBEntities context = new Teachers_DBEntities();

    private void SaveItem_Click(object sender, EventArgs e)
    {
        context.SaveChanges();
        MessageBox.Show("saved successfully");
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        teachers_tableBindingSource.DataSource = context.teachers_table.ToList();
    }

Upates for comments

I tested my "BindingSource" and found that it successfully understand if new record insert in "DataGridVeiw", but changes won't apply in database when I call context.savechanges();

context.savechanges() works fine when I update a cell, but it doesn't work when I try to insert a new record in my "DataGridView".

In my edmx file I mapped all columns correctly and primary key StoreGeneretedPattern property is set to Identity and its Entity Key property is set to true. Its auto-increment property in my SQL Server database file is set to true.

any help is appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
121 views
Welcome To Ask or Share your Answers For Others

1 Answer

context.savechanges() works fine when I update a cell, but it doesn't work when I try to insert a new record in my "DataGridView".

What do you mean by "it doesn't work"? New record does not appear in database? Of course it won't.

In this line

teachers_tableBindingSource.DataSource = context.teachers_table.ToList();

you're breaking DataSource's connection to context. Any new item inserted into it will be inserted not into teachers_table, but into List you created over it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...