从数据库填充时,WPF中的datagrid为空

时间:2014-08-04 13:04:20

标签: c# wpf datagrid

问题是,当我填充数据网格时,它会向我显示数据库中可用的行数,但行中的数据在数据网格中是空的。这是一个片段:

private void button1_Click(object sender, RoutedEventArgs e)
        {
            try
            {                
                connection.Open();
                SqlCommand command = new SqlCommand();
                command.CommandText = "select item_name from prod_info";
                cmdd.Connection = connection;
                Datatable table= new Datatable();
                SqlDataAdapter adapter = new SqlDataAdapter(command);
                adapter.Fill(table);
                dataGrid1.ItemsSource = table.DefaultView;
                connection.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

这是xaml代码:

<DataGrid AutoGenerateColumns="False" Height="308" HorizontalAlignment="Left" Margin="59,89,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="502" ItemsSource="{Binding }"/>

1 个答案:

答案 0 :(得分:1)

首先:AutoGenerateColumns =&#34; True&#34;

那么也许它也是必要的:

dataGrid1.ItemsSource = table.AsDataView();

解释here