我不能将WPF DataGrid绑定到ADO.净DataView

本文关键字:ADO DataView 绑定 DataGrid 不能 WPF | 更新日期: 2023-09-27 18:01:47

我无法将WPF DataGrid绑定到ADO。. NET DataView,我不知道我能用它做什么。我在MainWindow类中做了以下操作:

public partial class MainWindow : Window
{
    private DataSet _ds;
    /// <summary>
    ///This property is a data source for DataGrid.
    /// </summary>
    public DataView GridData { get { return _ds.Tables[0].DefaultView; } }
    /// <summary>
    /// Do fetching all records from table called DrugHandbook in database.
    /// </summary>
    public static void SelectAllRecordsFromDrugHandbook()
    {
        using (SqlConnection connection = new SqlConnection(_connectionString))
        {
            SqlCommand command = new SqlCommand("Select_All_Records_From_DrugHandbook", connection);
            command.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter adapter = new SqlDataAdapter(command);
            _ds = new DataSet();
            adapter.Fill(_ds);
        }
    }
}

然后在XAML中我写了以下内容:

<Window x:Class="ClientApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="DrugHandbook" Height="350" Width="525" WindowStartupLocation="CenterScreen">
    <Grid>
. . . . . . . . . . . . . .
        <DataGrid Name="dgDrugs" Grid.Row="2" Grid.Column="0" ItemsSource="{Binding 
Path=GridData, Mode=OneWay}" AutoGenerateColumns="False" CanUserAddRows="False" 
CanUserDeleteRows="False" CanUserReorderColumns="False" CanUserResizeColumns="False" 
CanUserResizeRows="False" CanUserSortColumns="False" SelectionMode="Single">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}"/>
                <DataGridTextColumn Header="Price" Binding="{Binding Path=Price}"/>
                <DataGridTextColumn Header="Form of Pack" Binding="{Binding Path=Pack}"/>
                <DataGridCheckBoxColumn Header="By Prescription" Binding="{Binding
 Path=Prescription}"/>
            </DataGrid.Columns>
        </DataGrid>
. . . . . . . . . . . . . .  
    </Grid>
</Window>

下面是druhandbook数据库表的脚本。"DrugId"字段为主键。

CREATE TABLE [dbo].[DrugHandbook](
    [DrugId] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [Name] [nvarchar](max) NULL,
    [Price] [money] NULL,
    [Pack] [nvarchar](max) NULL,
    [Prescription] [bit] NULL,
    )

在_ds DataSet填入数据后,此数据不显示在dgDrugs DataGrid中。_ds数据集被数据成功填充,我在调试模式下检查了它。我哪里做错了?请帮助。

我不能将WPF DataGrid绑定到ADO.净DataView

看看下面的Msdn链接,它确切地讨论了您想要实现的目标。

http://msdn.microsoft.com/en-us/library/ms752057 (v = vs.110) . aspx

密切关注数据上下文分配(数据集)、项模板(定义数据在数据网格中出现的方式)和itemssource(表名).

希望能有所帮助。