I have a DataGrid
in my application, whose XML definition is as follows:
<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>
As can be seen, the ItemsSource
is bound to a table named DBtable
, depending on which the rows/columns are automatically generated. Following is the code snippet used for connecting to and updating the database:
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;
}
The problem is, although any addition or edit operation done in the DataGrid
gets perfectly updated in the database, I am unfortunately unable to achieve the same behaviour for the deletion operation. The deletion is done in the source itself, so when I check the row count after a deletion operation (for which I use DBtable.Rows.RemoveAt()
), DBtable
shows me that the row is deleted, however the changes are not reflected in the database after the update attempt made using the SaveToDB()
function shown above. What should I do?
I found the problem. Apparently
Dbtable.Rows.RemoveAt(selectedIndex);
does not let the data table know that a deletion command has been issued. Hence, when an update command is run over the database, no deletion is seen and executed. Instead, using
row = DBtable.Rows[selectedIndex];
row.Delete();
solved the problem.