0

我只是学习 linq 并尝试使用 linq 和 ado.net 数据实体模型进行插入更新删除。现在我遇到了一些问题,当我插入一些数据时,datagridview 没有显示,我必须关闭程序并再次运行它以显示我正在输入的最新数据。这里的代码:

namespace TesDB
{
    public partial class Form1 : Form
    {
        private Database1Entities de = new Database1Entities();
        int index;

    public Form1()
    {
        InitializeComponent();

        var query = from x in de.MsEmployees
                    select x;

        dataGridView1.DataSource = query;
        dataGridView1.Refresh();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    public void loadtext()
    {
        textBox1.Text = dataGridView1.Rows[index].Cells[0].Value.ToString();
        textBox2.Text = dataGridView1.Rows[index].Cells[1].Value.ToString();
        textBox3.Text = dataGridView1.Rows[index].Cells[2].Value.ToString();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        string EmployeeID = dataGridView1.Rows[index].Cells[0].Value.ToString();

        var employee = (from x in de.MsEmployees
                        where x.EmployeeID == EmployeeID
                        select x).First();
        employee.EmployeeID  = textBox1.Text;
        employee.EmployeeName = textBox2.Text;
        employee.Salary = int.Parse(textBox3.Text);
        de.SaveChanges();
        Refresh();

    }



    private void button3_Click(object sender, EventArgs e)
    {
        string EmployeeID = dataGridView1.Rows[index].Cells[0].Value.ToString();
       // int id1 = int.Parse(EmployeeID);

        var Employee = (from x in de.MsEmployees
                        where x.EmployeeID == EmployeeID
                        select x).First();
        de.MsEmployees.DeleteObject(Employee);
        de.SaveChanges();
        Refresh();

    }

    private void button1_Click(object sender, EventArgs e)
    {
        string employeeID = dataGridView1.Rows[index].Cells[0].Value.ToString();

        var employee = (from x in de.MsEmployees
                        where x.EmployeeID == employeeID
                        select x.EmployeeID).First();

        MsEmployee me = new MsEmployee();
        me.EmployeeID = textBox1.Text;
        me.EmployeeName = textBox2.Text;
        me.Salary = int.Parse(textBox3.Text);
        de.AddToMsEmployees(me);
        de.SaveChanges();
       this.Refresh();
    }

    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {


        index = e.RowIndex;
        loadtext();

    }

}

}

`

我将refresh()这项工作用于更新和删除,但它不适用于插入,有人知道在我完成插入后如何刷新该表吗?

4

1 回答 1

2

制作一个 refresh() 方法并将您的 Query 粘贴到里面并在按钮后面调用它

      public void refresh()
      {
           //Paste ur Query here and call it behind the button_click Event
      }
于 2013-04-14T18:57:02.047 回答