2013-06-03 41 views
0

我是WPF新手。无法在WPF中绑定网格

我试图在WPF绑定数据网格。

我的代码:

con = new SqlConnection(conClass.conSTR); 
      try 
      { 
       con.Open(); 
       cmd = new SqlCommand("select * from login",con); 
       da = new SqlDataAdapter(cmd); 
       DataTable dt=new DataTable("login"); //DataSet ds = new DataSet(); 
       da.Fill(dt); 
       gv.ItemsSource = dt.DefaultView; 

      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 

XAML:

<Window x:Class="WpfTestApp.Window1" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="Window1" Height="428" Width="503" Loaded="Window_Loaded" xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"> 
    <Grid> 
     <TextBlock Margin="10" Text="This is a text block" Foreground="Red" TextTrimming="CharacterEllipsis" FontStretch="Normal" FontWeight="Bold"></TextBlock> 
     <TextBox Height="23" HorizontalAlignment="Left" Margin="10,29,0,0" Name="txtLoginID" VerticalAlignment="Top" Width="120" /> 
     <PasswordBox Name="txtPassword" PasswordChar="*" Margin="146,28,221,337"></PasswordBox> 
     <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="100,83,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" /> 
     <DataGrid AutoGenerateColumns="False" Height="247" HorizontalAlignment="Left" Margin="37,130,0,0" Name="gv" VerticalAlignment="Top" Width="303" /> 
    </Grid> 
</Window> 

有此代码没有错误。

但是还是我的网格未绑定表。

这只是表明我的水平线。

截图:

enter image description here

我不明白为什么我面临这个问题。

请指引我。

编辑:网后

<DataGrid AutoGenerateColumns="True">

enter image description here

+0

什么是您的XAML样子? –

+0

@LorentzVedeler更新了代码 – Freelancer

回答

1

变化<DataGrid AutoGenerateColumns="False">

<DataGrid AutoGenerateColumns="True"> 

添加RowHeight="25"到DataGrid中

+0

现在它只是显示我的行标题,没有数据,其他的东西,因为它显示行标题下方的水平线。 – Freelancer

+0

@Freelancer的rowHeight =“25”添加到数据网格 –

+0

没有,它使没有什么区别,可以看到我的编辑屏幕截图[更新] – Freelancer

1

试图改变自己的XAML和设置AutoGenerateColumns="True".

这使得电网为您的数据创建列。如果您未将其设置为true,则必须为要显示的列添加列定义。

+0

现在它只是显示我的行标题,没有数据,其他的东西,因为它显示在行标题下面的水平线。 – Freelancer

+0

看到我更新的屏幕截图。 – Freelancer

+0

你可以尝试手动创建列 –

2

尝试改变如下:

<DataGrid AutoGenerateColumns="True" DataContext="{Binding}"> 
+0

没有什么区别,这是一样的我已经uploded下面编辑截图 – Freelancer

+0

你检查你的ItemsSource是否包含数据,从DT加载后? gv.ItemsSource = dt。默认视图; –

+0

是的,它的工作。行高是问题,我排序它。 – Freelancer