Обновление изменений, внесенных в silverlight datagrid в базу данных
Я использую datagrid в своем приложении Silverlight. Я привязал столбцы этой datagrid к наблюдаемой коллекции, которая заполняется данными из службы WCF при загрузке страницы. Я хочу, чтобы любые изменения, которые я делаю в datagrid во время выполнения, то есть изменяю что-то или добавляю новую строку, или удаляю строку. он должен постоянно обновляться в базе данных при нажатии кнопки Сохранить. Как я могу этого достичь?
Моя страница Silverlight XAML.
<controls:ChildWindow xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" x:Class="slLHWProduct.PartsWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls" xmlns:controlsToolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit" Width="581" Height="321" Loaded="PartsWindow_OnLoaded" Title="Parts"> <Grid x:Name="LayoutRoot" Margin="2"> <StackPanel Orientation="Vertical"> <StackPanel Orientation="Horizontal"> <Button x:Name="btnAddBlankRow" Width="Auto" Height="22" Margin="0,0,5,0" HorizontalAlignment="Left" VerticalAlignment="Bottom" Click="btnAddBlankRow_Click" FontSize="12"> <Button.Content> <TextBlock Text="Add Blank Row" /> </Button.Content> </Button> <Button x:Name="btnCopySelectedRows" Width="Auto" Height="22" Margin="0,0,5,0" HorizontalAlignment="Left" VerticalAlignment="Bottom" Click="btnCopySelectedRows_Click" FontSize="12"> <Button.Content> <TextBlock Text="Copy Selected Rows" /> </Button.Content> </Button> <Button x:Name="btnDeleteSelectedRows" Width="Auto" Height="22" Margin="0,0,5,0" HorizontalAlignment="Left" VerticalAlignment="Bottom" Click="btnDeleteSelectedRows_Click" FontSize="12"> <Button.Content> <TextBlock Text="Delete Selected Rows" /> </Button.Content> </Button> <Button x:Name="btnSaveChanges" Width="Auto" Height="22" Margin="0,0,5,0" HorizontalAlignment="Left" VerticalAlignment="Bottom" Click="btnSaveChanges_Click" FontSize="12"> <Button.Content> <TextBlock Text="Save Changes" /> </Button.Content> </Button> <Button x:Name="btnExport" Width="Auto" Height="22" Margin="0,0,5,0" HorizontalAlignment="Left" VerticalAlignment="Bottom" Click="btnExport_Click" FontSize="12"> <Button.Content> <TextBlock Text="Export" /> </Button.Content> </Button> </StackPanel> <StackPanel> <ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto"> <sdk:DataGrid x:Name="dgPartsData" AutoGenerateColumns="False" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.HorizontalScrollBarVisibility="Visible" RowHeaderWidth="30" TabNavigation="Cycle" FontSize="12" SelectionMode="Single" HeadersVisibility="All" CanUserResizeColumns="True" CanUserSortColumns="True" CellEditEnded="DgPartsData_OnCellEditEnded" CurrentCellChanged="DgPartsData_OnCurrentCellChanged" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" > <sdk:DataGrid.Columns> <sdk:DataGridTemplateColumn Header="Name" SortMemberPath="Name"> <sdk:DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding Name}" FontSize="12" Margin="2" Tag="{Binding PartId}"></TextBlock> </DataTemplate> </sdk:DataGridTemplateColumn.CellTemplate> <sdk:DataGridTemplateColumn.CellEditingTemplate> <DataTemplate> <TextBox Text="{Binding Name,Mode=TwoWay}" FontSize="12" Margin="2" GotFocus="TextBox_GotFocus" LostFocus="TextBox_OnLostFocus"></TextBox> </DataTemplate> </sdk:DataGridTemplateColumn.CellEditingTemplate> </sdk:DataGridTemplateColumn> <sdk:DataGridTemplateColumn Header="Description" SortMemberPath="Description"> <sdk:DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding Description}" FontSize="12" Margin="2"></TextBlock> </DataTemplate> </sdk:DataGridTemplateColumn.CellTemplate> <sdk:DataGridTemplateColumn.CellEditingTemplate> <DataTemplate> <TextBox Text="{Binding Description,Mode=TwoWay}" FontSize="12" Margin="2" GotFocus="TextBox_GotFocus"></TextBox> </DataTemplate> </sdk:DataGridTemplateColumn.CellEditingTemplate> </sdk:DataGridTemplateColumn> <sdk:DataGridTemplateColumn Header="InUse" SortMemberPath="InUse"> <sdk:DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding InUse}" FontSize="12" Margin="2"></TextBlock> </DataTemplate> </sdk:DataGridTemplateColumn.CellTemplate> </sdk:DataGridTemplateColumn> </sdk:DataGrid.Columns> </sdk:DataGrid> </ScrollViewer> </StackPanel> </StackPanel> <controlsToolkit:BusyIndicator x:Name="biGlobal" BusyContent="Retrieving/Updating data, please wait..." IsBusy="False" /> </Grid> </controls:ChildWindow>
Мой Код C#.
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using LinqToSqlClientHelper; using slLHWProduct.LHWSLAdminServices; namespace slLHWProduct { public partial class PartsWindow : ChildWindow { public PartsWindow() { InitializeComponent(); this._ProductId = 0; biGlobal.IsBusy = true; } public class PartsData { public int PartId { get; set; } public string Name { get; set; } public string Description { get; set; } public int InUse { get; set; } } #region variables private int _ProductId = 0; public int ProductId { get { return _ProductId; } set { _ProductId = value; } } public LHWSLAdminServicesClient client; public ObservableCollection<PartsData> oc_Original; #endregion private void PartsWindow_OnLoaded(object sender, RoutedEventArgs e) { client = new LHWSLAdminServicesClient(); oc_Original = new ObservableCollection<PartsData>(); if (_ProductId > 0) { client.GetProductPartsAsync(_ProductId); client.GetProductPartsCompleted += new EventHandler<GetProductPartsCompletedEventArgs>(client_GetProductPartsCompleted); } } void client_GetProductPartsCompleted(object sender, GetProductPartsCompletedEventArgs e) { if (e.Result != null) { foreach (var item in e.Result) { oc_Original.Add(new PartsData { PartId = item.PartID, Name = item.Name, Description = item.DESCRIPTION, InUse = item.InUse.Value }); } dgPartsData.ItemsSource = oc_Original; biGlobal.IsBusy = false; } } private void OKButton_Click(object sender, RoutedEventArgs e) { GC.Collect(); this.DialogResult = true; } private void CancelButton_Click(object sender, RoutedEventArgs e) { GC.Collect(); this.DialogResult = false; } private void DgPartsData_OnCurrentCellChanged(object sender, EventArgs e) { dgPartsData.BeginEdit(); } private void TextBox_GotFocus(object sender, RoutedEventArgs e) { ((TextBox)sender).SelectAll(); } private void DgPartsData_OnCellEditEnded(object sender, DataGridCellEditEndedEventArgs e) { dgPartsData.CommitEdit(); dgPartsData.ItemsSource = oc_Original; } private void TextBox_OnLostFocus(object sender, RoutedEventArgs e) { dgPartsData.CommitEdit(); dgPartsData.ItemsSource = oc_Original; } private void btnAddBlankRow_Click(object sender, RoutedEventArgs e) { var item = oc_Original.Last().PartId; oc_Original.Add(new PartsData { PartId = item+1, Name = "", Description = "", InUse = 0 }); dgPartsData.ItemsSource = oc_Original; } private void btnCopySelectedRows_Click(object sender, RoutedEventArgs e) { } private void btnDeleteSelectedRows_Click(object sender, RoutedEventArgs e) { if (dgPartsData.SelectedItem != null) { dgPartsData.CommitEdit(); int PartID = Convert.ToInt32(((TextBlock)dgPartsData.Columns[0].GetCellContent(dgPartsData.SelectedItem)).Tag); MessageBox.Show(PartID.ToString()); var item = oc_Original.FirstOrDefault(i => i.PartId == PartID); oc_Original.Remove(item); dgPartsData.ItemsSource = oc_Original; } else { MessageBox.Show("Please select a part to delete"); } } private void btnSaveChanges_Click(object sender, RoutedEventArgs e) { } private void btnExport_Click(object sender, RoutedEventArgs e) { } } }
Мой сервис WCF.
[OperationContract]
публичный список<lhwclasses.admin.sp_lhwadmin_getproductpartsresult> GetProductParts(int ProductID)
{
LHWClasses.Администратор.Lhwsladmindatacontext db=новый LHWSLAdminDataContext();
ВАР рез = БД.sp_LhwAdmin_GetProductParts(Кодтовара);
возврат res.Список();
}
Пожалуйста, помогите мне разобраться с этой проблемой наилучшим образом .