删除键上的数据网格删除行按,但记录保留在数据库中,哪里出错了?

时间:2018-03-25 22:07:14

标签: c# winforms datagridview

我按如下方式设计数据库:

Figure

我的一些代码如下:

private void Form1_Load(object sender, EventArgs e)
    {
        string filename = string.Format("{0}//data.dat", Application.StartupPath);
        if (File.Exists(filename))
        {
            App.PhoneBook.ReadXml(filename);
        }
        phoneBookBindingSource.DataSource = App.PhoneBook;
        panel1.Enabled = false;
    }

并且关于data-grid view的key_down事件写道:

private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (MessageBox.Show("are you sure?, "Message",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {

                    phoneBookBindingSource.RemoveCurrent();





                }
            }
        }

当删除键时,按下数据网格中的一行,此行被删除但是当再次停止/启动时,我在数据网格中看到该记录。

某些数据库字段在数据网格中是不可见的。

在保存按钮的某些部分我写道:

phoneBookBindingSource.EndEdit();
App.PhoneBook.AcceptChanges();

另一部分是:

protected static PhoneData App
    {
        get
        {
            if (db == null)
            {
                db = new PhoneData();
            }
            return db;
        }
    }

我的代码中的问题在哪里?

1 个答案:

答案 0 :(得分:1)

您需要将数据源发送到save方法。像这样:

App.PhoneBook = (App.PhoneBook)phoneBookBindingSource;
App.PhoneBook.SaveXml(filename);

在SaveXmL中将电话簿序列化为XML,它看起来像这样:

public static void SaveXml(string FileName)  
    {  
        System.Xml.Serialization.XmlSerializer writer =   
            new System.Xml.Serialization.XmlSerializer(typeof(PhoneBook));  

        System.IO.FileStream file = System.IO.File.Create(path);  

        writer.Serialize(file, overview);  
        file.Close();  
    }