Hello everyone, I am trying to create a Datagrid in my WPF test project that will update existing data and add new data.
My Sql table has 2 columns, ID (int) and Test1 (nvchar 50).
Here is my xaml:
><Window x:Class="Testing.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid x:Name="dgTest" DisplayMemberPath="Testing" SelectedValue="{Binding ElementName=Test1, Path=SelectedItem.ID, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" SelectedValuePath="ID" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Height="268" Width="498"/>
<Button x:Name="btnSave" Content="Save" HorizontalAlignment="Left" Margin="222,291,0,0" VerticalAlignment="Top" Width="75" Click="btnSave_Click"/>
</Grid>
</Window></
Here is my Code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
namespace Testing
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
LoadTest();
}
#region Variables
#endregion
#region Constructors
dcTestDataContext dcTest = new dcTestDataContext();
#endregion
#region Classes
public class ObservableTest : ObservableCollection<Test>
{
public ObservableTest(dcTestDataContext dcTest)
{
foreach (Test Test1 in dcTest.Tests)
{
this.Add(Test1);
}
}
}
#endregion
#region Methods
private void LoadTest()
{
ObservableTest oTest = new ObservableTest(dcTest);
dgTest.ItemsSource = oTest.ToList();
}
private void SaveTest()
{
try
{
ObservableTest ocTest = new ObservableTest(dcTest);
Test testRow = dgTest.SelectedItem as Test;
int i = testRow.ID;
Test test = (from p in dcTest.Tests
where p.ID == testRow.ID
select p).Single();
test.Test1 = testRow.Test1;
dcTest.SubmitChanges();
MessageBox.Show("Row Updated Successfully.");
LoadTest();
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
return;
}
}
#endregion
#region Events
private void btnSave_Click(object sender, RoutedEventArgs e)
{
SaveTest();
}
#endregion
}
}
So my outcome is that my sql table will not update, but everything within my project works fine. I have tried stepping through my code numerous times, but to no availe.
Any help would be greatly appreciated.
Kind regards
Dean