【问题标题】:how to add data to database and show it in datagrid without restarting program?如何在不重新启动程序的情况下将数据添加到数据库并在数据网格中显示?
【发布时间】:2011-12-07 16:41:23
【问题描述】:

我可以将数据添加到数据库,但我只能在重新启动程序后才能看到它的结果。如何使添加数据成为可能,然后(立即。等待)在另一个带有数据网格的窗口中看到它?

【问题讨论】:

    标签: c# sql-server wpf


    【解决方案1】:

    我假设您将 DataGrids Items 属性绑定到您的数据,或类似的东西...您是否在您保存数据的任何类上实现了INotifyPropertyChanged?这也假设您有某种方式告诉您的 DataSource 刷新它的数据。如果您发出插入数据的 SQL 命令,并且您有一个 TableAdapter 或存储本地副本的东西,但您没有告诉 TableAdapter 从数据库刷新,您将永远看不到您的更改。

    这在使用 MVVM 时效果最好,但您也可以让它工作。本质上,您将 PropertyChanged 事件和处理程序添加到您的类。我通常会在我的属性设置器中调用处理程序,以及在我明确更改属性值的任何时候。

    这会告诉 UI 数据以某种方式发生了变化,并刷新它的视图表示。

    VB 示例

    Public MyClass
    Implements INotifyPropertyChanged
    
    Public Event PropertyChanged As PropertyChangedEventHandler _
        Implements INotifyPropertyChanged.PropertyChanged
    
    Protected Sub OnPropertyChanged(ByVal info As String)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))
    End Sub
    End Class
    

    C# 示例

    public class DemoCustomer  : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
    
        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
    }
    

    ObservableCollection

    我也是 ObservableCollection 的忠实粉丝。如果您有使用它的方法,我建议您使用它。它是 IEnumerable 并且已经在其上实现了 INotifyCollectionChanged。

    数据绑定说明

    假设您有一个用于包含数据的类(称为 MyData),在本例中是 Person 对象的集合(ObservableCollection People)。您的 XAML 可能如下所示。为简洁起见,这假定您的 MyData 类具有默认构造函数。

    <Window>
        <Window.Resources>
            <local:MyData x:key="mydata"/>
        </Window.Resources>
        <DataGrid DataContext="{StaticResource mydata}" ItemsSource="{Binding People}"/>
    </Window>
    

    通过这种方式,DataContext 描述数据的位置,而 ItemsSource 则告诉控件应该如何处理它。

    Code Project article dealing with databinding DataGrid to TableAdapter data.

    【讨论】:

    • 我还没有实现。我只是使用一个适配器及其方法 Update。
    • 嗯,好的。你可以看看底部的链接。 CodeProject 文章描述了许多数据绑定技术。我从来都不是处理数据的 DataTable/DataSet 方法的忠实粉丝。现在我几乎只使用 EntityFramework 或 NHibernate 并创建 CLR 类来使用。
    【解决方案2】:

    当您向数据库添加数据时,使用myDataGrid.DataBind() 重新绑定数据。

    【讨论】:

    • WPF 数据网格中现在有这样的方法。
    • 抱歉,我一定错过了 WPF 标签。你是如何将你的数据网格绑定到数据库的?
    • mydatagrid.datacontext = x; //x - datatable for examp.
    • CodeWarrior 是对的......他可能比我解释得更好。这里还有另一个帖子的链接,它比我解释得更好:stackoverflow.com/questions/5798936/…
    • DataContext 并没有真正像那样使用。在 ItemsControls(DataGrid 是其中的一部分)上,有一些属性(ItemsSource 和 Items)用于定义数据的来源。
    猜你喜欢
    • 1970-01-01
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    • 2019-07-14
    • 2014-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多