【问题标题】:WPF and SQL Server 2008 R2 DBWPF 和 SQL Server 2008 R2 数据库
【发布时间】:2012-02-18 12:30:38
【问题描述】:

现在当我按下按钮时,数据不会显示在列表框中,有什么帮助吗? 我想从数据库中获取数据并将其显示在列表框中,以便用户可以从中选择项目。 我正在使用 WPF 和 SQL Server 2008 R2 ..

private void button1_Click(object sender, RoutedEventArgs e) {

        SqlConnection myConnection = new SqlConnection("user id=userid;" +
                                   "password=password;server=localhost;" +
                                   "Trusted_Connection=yes;" +
                                   "database=db1; " +
                                   "connection timeout=30");

        DataSet ds = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter();
        try
        {
            myConnection.Open();

        }
        catch (Exception ex)
        {
            textBlock1.Text = "" + (ex.ToString());
        }

        da.SelectCommand = new SqlCommand("Select * FROM Products", myConnection);
        da.Fill(ds,"Products");
        listBox1.DataContext = ds;

    }

【问题讨论】:

    标签: sql wpf database sql-server-2008


    【解决方案1】:

    首先,它可能更容易绑定到 itemsSource 而不是 datacontext

    其次,您尝试将列表框直接绑定到数据集,我认为这是不可能的。我将创建一个 dataview 属性并将其设置为 ds.Tables[0].DefaultView。然后在您的列表框 xaml 代码中显示放置的列:

    <ListView ItemsSource="{Binding Path=myDataViewProperty}">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Column1"  DisplayMemberBinding="{Binding Column1}"/>
                <GridViewColumn Header="Column2" DisplayMemberBinding="{Binding Column2}"/>
            </GridView>
        </ListView.View>
    </ListView>
    

    第三,你确定列表框是最适合你想要显示的控件吗?数据网格可能是更好的选择。

    【讨论】:

      【解决方案2】:

      你必须定义你的绑定,单独设置 DataContext 不会填充数据,它只是声明绑定数据的来源。

      <ListBox ItemsSource="{Binding Tables[0]}">
        <ListBox.ItemTemplate>
          <DataTemplate>
            <TextBlock Text="{Binding ProductName}"/>
          </DataTemplate>
        </ListBox.ItemTemplate>
      </ListBox>
      

      或者如果您只想在列表框中显示单个值:

      <ListBox ItemsSource="{Binding Tables[0]}" DisplayMemberPath="ProductName"/>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-04
        • 2011-08-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多