【问题标题】:Getting Data from SQL Server to populate in DataGrid in C# WPF从 SQL Server 获取数据以填充 C# WPF 中的 DataGrid
【发布时间】:2014-03-03 15:47:18
【问题描述】:

我正在尝试从我的数据库中获取数据以填充到我的 WPF 应用程序的 DataGrid 中。我的数据库连接到 VisualStudio 2012 并有一个 .dml 文件。当您单击主窗口上的“烟花目录”按钮时,数据应该会加载。

据我所知,我拥有所有必要的参考资料,并且在构建和调试时没有出错。新窗口也会打开,并显示网格,但没有数据。这是一些代码

FireworkCatalog.xaml

    <DataGrid Name="FireworkCatalogGrid" HorizontalAlignment="Left" Margin="32,24,0,0" VerticalAlignment="Top" Height="236" Width="508" SelectionChanged="FireworkCatalogGrid_Window_Loaded" Background="#FF7C7878" BorderBrush="#FFDC3B18">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Type" Binding="{Binding Path=Type}"/>
            <DataGridTextColumn Header="Class" Binding="{Binding Path=Class}"/>
            <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}"/>
            <DataGridTextColumn Header="description" Binding="{Binding Path=Description}"/>

       </DataGrid.Columns>


FireworkCatalog.xaml.cs

  private void FireworkCatalogGrid_Window_Loaded(object sender, SelectionChangedEventArgs e)
    {

        FireworkDataDataContext data = new FireworkDataDataContext();
        List <fireworkType> fireworks = (from f in data.fireworkTypes
                                         select f) .ToList();
        FireworkCatalogGrid.ItemsSource = fireworks;
    }

MainScreen.xaml.cs

 private void FwkCatalog_btn_Click(object sender, RoutedEventArgs e)
  {
       FireworkCatalog catalog = new FireworkCatalog();
       catalog.ShowDialog();
  }

这里是使用 Linq to SQL 数据库时自动生成的一些代码,因此您可以看到到目前为止的表名和列。

FireworkData.designer.cs

[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.fireworkType")]
public partial class fireworkType
{

    private string _Type;

    private string _Class;

    private string _Name;

    private string _Description;

    public fireworkType()
    {
    }
    }

非常感谢任何帮助,或任何其他关于如何将数据从我的 SQL Server 获取到我的 WPF 的想法。


编辑。

这是另一组代码,用于查看如何评估每列的数据

[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Type", DbType="VarChar(50) NOT NULL", CanBeNull=false)]
    public string Type
    {
        get
        {
            return this._Type;
        }
        set
        {
            if ((this._Type != value))
            {
                this._Type = value;
            }
        }
    }

【问题讨论】:

    标签: c# sql wpf xaml datagrid


    【解决方案1】:

    fireworkType 类型是否有任何公共属性?您需要将 TypeClassNameDescription 公开为公共属性,以便绑定能够获取值。

    private string _Type;
    public string Type
    {
        get { return _Type; }        
    }
    

    作为一个单独的问题,如果您希望这些是可编辑的,您需要添加设置器。如果您想更新这些值并让它们自动显示在网格中,您需要实现INotifyPropertyChanged

    【讨论】:

    • 每一列的值已经设置了一个公共属性,见上面的编辑。
    猜你喜欢
    • 2011-09-09
    • 1970-01-01
    • 2012-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多