我的应用程序中有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
的表,具体取决于自动生成的行/列。以下是用于连接和更新数据库的代码段:
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()
函数进行更新尝试后反映在数据库中。我该怎么办?
答案 0 :(得分:0)
我发现了问题。显然
Dbtable.Rows.RemoveAt(selectedIndex);
不会让数据表知道已发出删除命令。因此,当在数据库上运行更新命令时,不会看到并执行删除。相反,使用
row = DBtable.Rows[selectedIndex];
row.Delete();
解决了这个问题。
答案 1 :(得分:0)
类似的东西也让我很困惑。对于那些可能在以后搜索时遇到此页面的人来说,这是一个解决方案。
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);
}
}
}