Аз съм нов в разработката на Windows, опитвам се да избера добър модел за управление на база данни, така че да мога да го използвам за бъдещите си приложения. Това, което открих, е това поведение, Създайте локална база данни->свържете го с wpf DataGridView и DataSet->Използване на sql адаптер за отразяване на промяната на данните в базата данни. Ето какво написах:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:DB" x:Class="DB.MainWindow"
Title="MainWindow" Height="350" Width="800" Loaded="Window_Loaded">
<Window.Resources>
<local:DataBaseMioDataSet x:Key="dataBaseMioDataSet"/>
<CollectionViewSource x:Key="gallerieViewSource" Source="{Binding Gallerie, Source={StaticResource dataBaseMioDataSet}}"/>
</Window.Resources>
<Grid DataContext="{StaticResource gallerieViewSource}">
<DataGrid x:Name="gallerieDataGrid" RowDetailsVisibilityMode="VisibleWhenSelected" Margin="10,10,210,109" ItemsSource="{Binding}" EnableRowVirtualization="True" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn x:Name="idColumn" Width="SizeToHeader" Header="Id" Binding="{Binding Id}"/>
<DataGridTextColumn x:Name="idgalleriaColumn" Width="SizeToHeader" Header="idgalleria" Binding="{Binding idgalleria}"/>
<DataGridTextColumn x:Name="pathImgColumn" Width="SizeToHeader" Header="path Img" Binding="{Binding pathImg}"/>
</DataGrid.Columns>
</DataGrid>
<TextBox x:Name="idgalleriaAdd" HorizontalAlignment="Left" Height="23" Margin="612,14,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="98"/>
<TextBox x:Name="pathgalleriaAdd" HorizontalAlignment="Left" Height="23" Margin="612,51,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="98"/>
<Label x:Name="labell" Content="idgalleria" HorizontalAlignment="Left" Margin="724,14,0,0" VerticalAlignment="Top" />
<Label x:Name="labell_Copy" Content="pathgalleria" HorizontalAlignment="Left" Margin="715,51,0,0" VerticalAlignment="Top" />
<Button Content="Add" HorizontalAlignment="Left" Margin="612,96,0,0" VerticalAlignment="Top" Width="170" Click="addrow"/>
<Button Content="Delete" HorizontalAlignment="Left" Margin="612,145,0,0" VerticalAlignment="Top" Width="170" Click="deleterow"/>
</Grid>
Code Behind :
private void Window_Loaded(object sender, RoutedEventArgs e)
{
DB.DataBaseMioDataSet dataBaseMioDataSet = ((DB.DataBaseMioDataSet)(this.FindResource("dataBaseMioDataSet")));
// Carica i dati nella tabella Gallerie. Se necessario, è possibile modificare questo codice.
DB.DataBaseMioDataSetTableAdapters.GallerieTableAdapter dataBaseMioDataSetGallerieTableAdapter = new DB.DataBaseMioDataSetTableAdapters.GallerieTableAdapter();
dataBaseMioDataSetGallerieTableAdapter.Fill(dataBaseMioDataSet.Gallerie);
System.Windows.Data.CollectionViewSource gallerieViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("gallerieViewSource")));
gallerieViewSource.View.MoveCurrentToFirst();
}
public static SqlDataAdapter GetTableRecord(DataBaseMioDataSet datSet)
{
SqlConnection connection = new SqlConnection(Properties.Settings.Default.DataBaseMioStringaConnessione);//Set the connection to the SQL server
connection.Open();
string query = "SELECT * from Gallerie";
SqlCommand command = new SqlCommand(query, connection);
SqlDataAdapter adp = new SqlDataAdapter(command);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(adp);
adp.UpdateCommand = commandBuilder.GetUpdateCommand();
adp.InsertCommand = commandBuilder.GetInsertCommand();
adp.DeleteCommand = commandBuilder.GetDeleteCommand();
return adp;
}
public void deleterow(object sender, RoutedEventArgs e)
{
DB.DataBaseMioDataSet DataBaseMioDataSet = ((DB.DataBaseMioDataSet)(this.FindResource("dataBaseMioDataSet")));
int totalrow= DataBaseMioDataSet.Tables["Gallerie"].Rows.Count;
int lastrow= totalrow- 1;
DataBaseMioDataSet.Tables["Gallerie"].Rows[lastrow].Delete();
SqlDataAdapter adp = GetTableRecord(DataBaseMioDataSet);
adp.Fill(DataBaseMioDataSet, "Gallerie");
adp.Update(DataBaseMioDataSet, "Gallerie");
}
С този код мога да визуализирам правилно данните в моята таблица "Gallerie". Проблемът идва с модификацията на таблицата, мога правилно да изтрия последния ред от набора от данни (виждам, че изчезва от dataGrid), но adp.Update() не изтрива същия ред от реалната база данни, така че когато рестартирам приложението, записът, който съм изтрил, идва отново... Не се показва съобщение за грешка. Как мога да направя, за да изтрия "наистина" запис от моята база данни?
РЕДАКТИРАНЕ
Прочетох някъде, че SelectCommand трябва да се създава автоматично с Adapter init... Както и да е, опитах се да добавя:
string query = "SELECT * from Gallerie";
SqlCommand command = new SqlCommand(query, connection);
adp.SelectCommand = command;
Това не работи, може би правя нещо друго нередно?