【问题标题】:WPF DataGrid deleted rows don't get updated (deleted) in the databaseWPF DataGrid 删除的行不会在数据库中更新(删除)
【发布时间】:2015-04-23 19:03:35
【问题描述】:

我的应用中有一个DataGrid,其XML定义如下:

<DataGrid x:Name="grid"
          DockPanel.Dock="Top"
          Visibility="{Binding gridVisibility}"
          CellStyle="{StaticResource ValidationReadyCellStyle}"
          IsSynchronizedWithCurrentItem="True"
          HorizontalAlignment="Stretch"
          HorizontalContentAlignment="Stretch"
          VerticalContentAlignment="Stretch"
          ColumnWidth="*"
          ItemsSource="{Binding DBtable, ValidatesOnExceptions=False,
          NotifyOnSourceUpdated=True, TargetNullValue={x:Static system:String.Empty}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
          AutoGenerateColumns="True" AutoGeneratingColumn="grid_OnAutoGeneratingColumn" CanUserAddRows="True"
          BeginningEdit="grid_OnBeginningEdit" PreviewKeyDown="grid_OnPreviewKeyDown" RowEditEnding="grid_OnRowEditEnding" CellEditEnding="grid_OnCellEditEnding">
          <DataGrid.RowValidationRules>
              <local:RowValidationChecker ValidationStep="UpdatedValue"/>
          </DataGrid.RowValidationRules>
</DataGrid>

可以看出,ItemsSource 绑定到名为DBtable 的表,具体取决于自动生成的行/列。以下是用于连接和更新数据库的代码 sn-p:

public bool SaveToDB(DataTable table, string tableName)
{
    var msSqlConnectionClass = new MsSqlConnectionClass(MsSqlLogin.Default.Server,
                                                            MsSqlLogin.Default.LoremIpsumDB, MsSqlLogin.Default.UID,
                                                            MsSqlLogin.Default.Password, MsSqlLogin.Default.WinAuth);
    SqlConnection msSqlConnection = msSqlConnectionClass.getMsSqlConnection();
    msSqlConnection.Open();
    try
    {
        string strSQL = "SELECT * FROM " + tableName;
        SqlDataAdapter da = new SqlDataAdapter(strSQL, msSqlConnection);
        SqlCommandBuilder command = new SqlCommandBuilder(da);
        da.UpdateCommand = command.GetUpdateCommand();
        da.DeleteCommand = command.GetDeleteCommand();
        da.InsertCommand = command.GetInsertCommand();
        da.Update(table);
        msSqlConnection.Close();
    }
    catch (Exception e)
    {
        ServiceLog.AddLogInfo(e.ToString());
        msSqlConnection.Close();
        return false;
    }
    return true;
}

问题是,尽管在DataGrid 中完成的任何添加或编辑操作都会在数据库中得到完美更新,但遗憾的是我无法为删除操作实现相同的行为。删除是在源本身中完成的,所以当我在删除操作(我使用DBtable.Rows.RemoveAt())之后检查行数时,DBtable 显示该行已被删除,但更改并未反映在数据库中在使用上面显示的SaveToDB() 函数进行更新尝试之后。我该怎么办?

【问题讨论】:

    标签: sql wpf database sql-update wpfdatagrid


    【解决方案1】:

    我发现了问题。显然

    Dbtable.Rows.RemoveAt(selectedIndex);
    

    不让数据表知道已发出删除命令。因此,当对数据库运行更新命令时,不会看到并执行任何删除操作。相反,使用

    row = DBtable.Rows[selectedIndex];
    row.Delete();
    

    解决了这个问题。

    【讨论】:

      【解决方案2】:

      类似的事情也让我感到困惑。对于以后搜索时可能会遇到此页面的人来说,这是一个解决方案。

      public DataTable GetMembers()
              {
                  conn = new SqlCeConnection(@"Data Source = DataModel.sdf");
                  dataAdapter = new SqlCeDataAdapter("Select * from Members", conn);
                  commandBuilder = new SqlCeCommandBuilder(dataAdapter);
                  dataTable = new DataTable();
                  dataAdapter.Fill(dataTable);
                  dataTable.RowChanged += new DataRowChangeEventHandler(dataTable_RowChanged);
                  dataTable.RowDeleted += new DataRowChangeEventHandler(dataTable_RowDeleted);
                  dataTable.DefaultView.ListChanged += DefaultView_ListChanged;
                  return dataTable;
              }
      
              void DefaultView_ListChanged(object sender, System.ComponentModel.ListChangedEventArgs e)
              {
                  if (e.ListChangedType == System.ComponentModel.ListChangedType.ItemDeleted)
                  {
                      try
                      {
                          dataAdapter.Update(dataTable);
                      }
                      catch (Exception ex)
                      {
                          System.Windows.MessageBox.Show(ex.Message);
                      }
                  }
              }
      

      【讨论】:

        猜你喜欢
        • 2012-02-11
        • 1970-01-01
        • 2014-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-20
        • 2023-03-24
        • 2011-09-17
        相关资源
        最近更新 更多