WPF Datagrid使用ObservableCollection和Linq to SQL [英] WPF Datagrid using an ObservableCollection and Linq to SQL

查看:83
本文介绍了WPF Datagrid使用ObservableCollection和Linq to SQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


大家好,我正在尝试在我的WPF测试项目中创建一个Datagrid,它将更新现有数据并添加新数据。



我的Sql表有2列,ID(int)和Test1(nvchar 50)。



这是我的xaml:



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
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            // Initializes all the objects.

            InitializeComponent();

            // Runs my Loadtest method.

            LoadTest();
        }

        #region Variables


        #endregion

        #region Constructors

        // Creates a new instance of my data context
        
        dcTestDataContext dcTest = new dcTestDataContext();

        #endregion

        #region Classes

        public class ObservableTest : ObservableCollection<Test>
        {
            public ObservableTest(dcTestDataContext dcTest)
            {
                //Creates an ObservableCollection class
                //Then adds the Test1 field and ID field from the ling to sql table.

                foreach (Test Test1 in dcTest.Tests)
                {
                   this.Add(Test1);
                }

            }
        }

        #endregion

        #region Methods

        private void LoadTest()
        {  
  
            //Creates an object of my ObservableTest class
            //Assigns the data within my class to the item source of the datagrid

            ObservableTest oTest = new ObservableTest(dcTest);
            dgTest.ItemsSource = oTest.ToList();

        }


        private void SaveTest()
        {
            // Create a new instance of my ObservableTest class.
            // Create a new instance of Test and assign it the value of the selected item.
            // Create a variable i and assign it the ID of the selected item.

            // Creates a new instance of Test and iterates through the table to match the ID of the
            // selected item and the ID in the dcTest (datacontext).
            // Sets the Test1 field in the table with the Test1 field from the dcTest.

            // Submits the changes from dgTest to the dcTest and then creates a message box
            // to tell the user the update was succesful, before refreshing the datagrid.

            // Creates a messagebox to catch any exceptions, which gives the details of the exception.

                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)
        {
            // Runs my Savetest method, when the user clicks the save button.

            SaveTest();
        }

        #endregion       

      
    }
}







所以我的结果是我的sql表不会更新,但我项目中的所有内容都有效精细。我曾尝试多次单步执行我的代码,但没有尝试过。



我们非常感谢任何帮助。







亲切的问候



Dean




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

推荐答案

好吧,我想这可以回答你的问题 http://social.msdn.microsoft.com/论坛/ en-US / wpf / thread / a29ae103-f516-4252-9c90-1aa4c5874a43 [ ^ ]这里是一个sugested变种的实现 http://www.dotnetcurry.com/ShowArticle.aspx?ID=563 [ ^ ]。顺便说一下 http://msdn.microsoft.com/en-us/library/bb546190.aspx [ ^ ]说
well, i think this may answer your question http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/a29ae103-f516-4252-9c90-1aa4c5874a43[^]and here is an implementaion of the sugested workaround http://www.dotnetcurry.com/ShowArticle.aspx?ID=563[^]. by the way http://msdn.microsoft.com/en-us/library/bb546190.aspx[^] says
引用:

LINQ to SQL将LINQ查询转换为SQL以便在数据库上执行。结果是强类型IEnumerable。因为这些对象是普通的公共语言运行库(CLR)对象,所以可以使用普通的对象数据绑定来显示结果。另一方面,更改操作(插入,更新和删除)需要额外的步骤。

LINQ to SQL translates LINQ queries to SQL for execution on a database. The results are strongly typed IEnumerable. Because these objects are ordinary common language runtime (CLR) objects, ordinary object data binding can be used to display the results. On the other hand, change operations (inserts, updates, and deletes) require additional steps.

另请参阅

Quote:

对象状态和更改跟踪



调试:启用DataContext日志记录,如


debugging: enable DataContext logging like

db.Log = Console.Out;

,我读了这个

引用:

LinqToSql不能在没有定义主键的表上工作,你可以使用LinqToSql读取表的数据但是你无法更新没有定义主键的表数据,因为它没有为没有主键的表实现INotifyChanged接口。

LinqToSql doesn’t work on the tables which do not have primary key defined, you can read the data of a table using LinqToSql but you cannot update the table data with out having primary key defined, because it doesnt implement INotifyChanged interface for the table which do not have primary key.


它有一个主键。



我解决了这个问题。



private void NewSaveTest()

{



try

{

ObservableTest ocTest = new ObservableTest(dcTest);



测试testRow = dgTest.SelectedItem作为测试;



dcTest.Tests.InsertOnSubmit(testRow);



ocTest.Add(testRow);



dcTest.SubmitChanges();



MessageBox.Show(行已成功更新。);

LoadTest();



}



catch(例外情况)

{



MessageBox.Show(Ex.Message);



return;

}



}
It has a primary key.

I solved the issue, with this.

private void NewSaveTest()
{

try
{
ObservableTest ocTest = new ObservableTest(dcTest);

Test testRow = dgTest.SelectedItem as Test;

dcTest.Tests.InsertOnSubmit(testRow);

ocTest.Add(testRow);

dcTest.SubmitChanges();

MessageBox.Show("Row Updated Successfully.");
LoadTest();

}

catch (Exception Ex)
{

MessageBox.Show(Ex.Message);

return;
}

}


这篇关于WPF Datagrid使用ObservableCollection和Linq to SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆