【发布时间】:2014-05-04 10:00:56
【问题描述】:
我无法将 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>
这里是 DrugHandbook 数据库表的脚本。 “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 数据集被数据填充成功,我在调试模式下检查了它。我在这里做错了什么?请帮忙。
【问题讨论】: