将更改从DataGridView保存回SQL数据库? [英] Saving changes from a DataGridView back to an SQL database?

查看:133
本文介绍了将更改从DataGridView保存回SQL数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个DataGridView,该数据库显示SQL数据库(GSM.sdf)中的数据,并在按下保存按钮时将对DataGridView所做的更改保存回数据库。数据显示正常,但是按保存按钮时没有任何反应。我一直在关注该线程的最佳答案:

I'm trying to make a DataGridView that displays data from an SQL database (GSM.sdf) and saves changes made to the DataGridView back to the database when a save button is pressed. The data displays fine, but nothing happens when the save button is pressed. I've been following the top answer from this thread:

http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/98bc0b4d-a2ea-4b74-81f0-473da624528a

但是没有成功。这是我的代码:

But it isn't working out. Here is my code:

namespace WindowsFormsApplication5
{
    public partial class Zeelot : Form
    {
        DataTable table = new DataTable();
        SqlCeDataAdapter z;
        DataSet gSMDataSet = new DataSet();
        public Zeelot()
        {
            InitializeComponent();
        }
        private void Zeelot_Load(object sender, EventArgs e)
        {
            string b = @"Data Source =.\SQLEXPRESS;database=GSM;Integrated Security=FALSE;Connection Timeout=30;User Instance=FALSE";
            SqlCeConnection conn = new SqlCeConnection(b);
            conn.Open();
            string cd = "SELECT * FROM PhoneNumbers";
            z = new SqlCeDataAdapter(cd, conn);
            z.Fill(gSMDataSet, "PhoneNumbers");
            table = gSMDataSet.Tables[0];
            conn.Close();
            dataGridView1.DataSource = table;
        }
        private void SaveButton_Click(object sender, EventArgs e)
        {
            SqlCeCommandBuilder local_SqlCommandBuilder = new SqlCeCommandBuilder(z);
            local_SqlCommandBuilder.ConflictOption = System.Data.ConflictOption.OverwriteChanges;
            z.UpdateCommand = local_SqlCommandBuilder.GetUpdateCommand();
            z.Update(((System.Data.DataTable)this.dataGridView1.DataSource));
            ((System.Data.DataTable)this.dataGridView1.DataSource).AcceptChanges();
        }

    }
}


推荐答案

我相信您的问题出在将数据源投射到System.Data.DataTable的地方

I believe your problem lies where you are casting a DataSource to System.Data.DataTable

尝试z.Update(gSMDataSet);

Try z.Update(gSMDataSet);

我也不相信您需要AcceptChanges()

I also don't believe you need AcceptChanges()

这篇关于将更改从DataGridView保存回SQL数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆