【问题标题】:Update changed DataGrid to the database?将更改的 DataGrid 更新到数据库?
【发布时间】:2012-02-23 06:10:52
【问题描述】:

好吧,伙计们,

经过多次阅读并在这里找到解决方案后,我只需要问这个。 我已经搜索过它,但它并没有帮助我解决这个问题。 另外,请原谅我的语法错误......

有什么问题? 我加载了一个带有组合框的 WPF 表单。这个组合框从我的数据库中的所有表中获取所有名称。我选择了一个表名并按下一个按钮来用所选表填充 DataGrid (WPF)。这一切都完美无缺。但是,当我更改单元格或添加/删除行或列时,我必须将其更新到数据库中。 这就是我卡住的地方。我通过一种不太理想的方式让它工作。所以这就是为什么我问是否有更好的解决方案。

//fill the datagrid with data from chosen table in combobox!            
selectedTable = cboxTables.SelectedItem.ToString();
dataset = db.getDataFromTable(selectedTable);
datatable = dataset.Tables[selectedTable];
datagridAdmin.ItemsSource = datatable.DefaultView;

当 DataGrid 中的选择发生变化时,我将“提交”按钮设置为活动状态,调用此代码:

db.updateTable(selectedTable, datatable);

请注意,“db”是我的数据库类的一个实例。方法如下:

public bool updateTable(String tableName, DataTable datatable)
{
    using (SqlBulkCopy bulkcopy = new SqlBulkCopy(thisConnection.ConnectionString, SqlBulkCopyOptions.CheckConstraints))
    {
        //Set destination table name
        //to table previously created.
        bulkcopy.DestinationTableName = tableName;

        try
        {
            thisCommand = new SqlCommand("DELETE FROM " + tableName, thisConnection);
            thisCommand.ExecuteNonQuery();
            bulkcopy.WriteToServer(datatable);
        }
        catch (Exception ex)
        {
            logger.WriteLine(applicationName, ex.Message);
        }
    }
}

但问题是,第一列是一个自动增量 ID,每次我提交更改的 DataGrid 时都会不断提高。 难道没有更好的方法吗?

谢谢!

PS:我在 Visual Studio 2010 中使用 WPF 中的 C# 进行编码。

【问题讨论】:

    标签: c# sql wpf datagrid


    【解决方案1】:

    简而言之,对于您提供的方法,您最好在调用批量复制之前使用 Truncate table 方法,这会将 Identity 列重置为 0:

    thisCommand = new SqlCommand("TRUNCATE TABLE " + tableName, thisConnection);
    

    但是,任何一种方法都会导致数据库中的外键出现问题。我不确定您是如何在数据库类中检索数据的,但我会考虑使用 SqlCommandBuilder 更新您的数据库,而不是在每次更新时删除并重新插入所有数据。

    编辑

    进一步解释我对 SqlCommandBuilder 的建议。

    如下所示的 ViewModel 应该允许使用 SqlCommandBuilder(注意:这已大大减少,实际上这需要更好的验证、异常和事件处理,但大致的想法就在那里):

    public class YourViewModel
    {
        private SqlDataAdapter adapter;
        private DataTable table;
        private SqlCommandBuilder commandBuilder;
        public DataTable Table { get { return table; } set { table = value; } }
        public void LoadTable(string connectionString, string tableName, int[] primaryKeyColumns)
        {
            adapter = new SqlDataAdapter(string.Format("SELECT * FROM {0}", tableName), connectionString);
            table = new DataTable();
            adapter.Fill(table);
            List<DataColumn> primaryKeys = new List<DataColumn>();
            for (int i = 0; i < primaryKeyColumns.Length; i++) 
            {
                 primaryKeys.Add(table.Columns[primaryKeyColumns[i]]);
            }
            table.PrimaryKey = primaryKeys.ToArray();
            commandBuilder = new SqlCommandBuilder(adapter);
            commandBuilder.GetUpdateCommand();
        }
        public int Update()
        {
            if (table == null || table.Rows.Count == 0 || adapter == null) 
            {
                 return 0;
            }
            if (table.PrimaryKey.Length == 0)
            {
                throw new Exception("Primary Keys must be defined before an update of this nature can be performed");
            }
            else
            {
                return adapter.Update(table);
            }
        }
    }
    

    将 Table 属性绑定到网格视图,然后在需要时调用 Update 方法。您甚至可以将更新绑定到表的 rowchanged 事件等以自动更新数据库。 Code Project 有一篇关于 WPF、数据网格和数据库集成的不错的文章。

    【讨论】:

    • 你说的 TRUNCATE 选项不起作用。它说更新成功,但刷新后仍然有旧值。关于 SqlCommandBuilder,我尝试实现它,但是当它需要一个我在更新之前不使用的 SqlCommand 时,如何让它生成一个 UPDATE 命令?
    • 我已经更正了我的截断语句,并尝试通过使用 SqlDataAdapter 来扩展我的意思。虽然没有看到你的源代码很难准确地说出如何使用它,但我已经尽量做到通用。
    • 非常感谢。我认为这已经足够了。将在下周尝试制定您的示例。如果它不起作用,那么我会回来解释问题。
    猜你喜欢
    • 2018-01-19
    • 1970-01-01
    • 2014-04-11
    • 2014-01-23
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    相关资源
    最近更新 更多