【问题标题】:Populating a WPF listbox with items from an SQL (SDF) database使用 SQL (SDF) 数据库中的项目填充 WPF 列表框
【发布时间】:2011-04-03 07:17:07
【问题描述】:

我一直在寻找如何做到这一点很长一段时间,我还没有设法得到关于这个问题的直接答案,所以希望你们中的一个 StackOverflow 用户能够在这里帮助我。我有一个名为 CategoryList 的 WPF ListBox 和一个名为 ProgramsList.sdf 的 SDF 数据库(有两个名为 CategoryList 和 ProgramsList 的表)。我希望我的程序做的是从 CategoryList 表中获取类别名称并将它们列出在名为 CategoryList 的 ListBox 控件中。

这是我尝试过的代码,但它只会导致我的程序崩溃。

    SqlConnection myConnection = new SqlConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "ProgramsList.sdf");
    SqlDataReader myReader = null;

    myConnection.Open();
    CategoryList.Items.Clear();
    SqlDataReader dr = new SqlCommand("SELECT Name FROM CategoryList ORDER BY Name DESC", myConnection).ExecuteReader();

    while (myReader.Read())
    {
        CategoryList.Items.Add(dr.GetInt32(0));
    }
    myConnection.Close();

谁能帮帮我?提前致谢!

【问题讨论】:

  • 我终于找到了答案,男孩,我是不是很傻!我在我的后端代码中使用了 SQL Server,这是一个用于网络客户端-服务器应用程序的框架,而我应该将 SQL Compact Edition 用于本地桌面程序!我没有意识到 MDF 是用于 SQL Server 的,而 SDF 是用于 MDF 的。无论如何,我结合了 Nate 和 Stratton 的代码并修改它们以使用 SQL CE。谢谢大家的帮助!
  • 这里,如果你需要加载字符串值意味着你需要输入dr.GetString(1)。如果您需要加载 int 值,则意味着您需要输入dr.GetInt32(0)。它对我有用。 Check Here!!

标签: c# sql wpf listbox populate


【解决方案1】:

更好的方法是将列表绑定到您创建的对象。这样您就可以为 DisplayMemberPath(您所看到的)和 SelectedValuePath(您的程序内部值)指定属性。

这是您的主要 XAML 代码。请注意,按钮的单击方法将显示 ComboBox 的当前选定值。这将使以后的事情变得容易。希望这不是矫枉过正,但它展示了一些使 WPF 变得简单的原则。

namespace WPFListBoxSample {

public partial class Window1 : Window

{

    WPFListBoxModel model = new WPFListBoxModel();

    public Window1()
    {
        InitializeComponent();
        this.Loaded += new RoutedEventHandler(Window1_Loaded);
    }

    void Window1_Loaded(object sender, RoutedEventArgs e)
    {
        GetData();
        this.DataContext = model;
    }

    public void GetData()
    {
        //SqlConnection myConnection = new SqlConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "ProgramsList.sdf");
        SqlConnectionStringBuilder str = new SqlConnectionStringBuilder();
        str.DataSource="192.168.1.27";
        str.InitialCatalog="NorthWnd";
        str.UserID="sa";
        str.Password="xyz";
        SqlConnection myConnection = new SqlConnection(str.ConnectionString);

        SqlDataReader myReader = null;

        myConnection.Open();
        SqlDataReader dr = new SqlCommand("SELECT CategoryId, CategoryName FROM Categories ORDER BY CategoryName DESC", myConnection).ExecuteReader();

        while (dr.Read())
        {
            model.Categories.Add(new Category { Id = dr.GetInt32(0), CategoryName = dr.GetString(1) });
        }
        myConnection.Close();
    }

    private void myButton_Click(object sender, RoutedEventArgs e)
    {
        if (this.myCombo.SelectedValue != null)
            MessageBox.Show("You selected product: " + this.myCombo.SelectedValue);
        else
            MessageBox.Show("No product selected");
    }
}

}

XAML

    <Grid>
    <StackPanel>
        <ComboBox x:Name="myCombo" ItemsSource="{Binding Categories}" DisplayMemberPath="CategoryName"  SelectedValuePath="Id" />
        <Button x:Name="myButton" Content="Show Product" Click="myButton_Click"/>
    </StackPanel>
</Grid>

您自己的用于表示类别的对象

namespace WPFListBoxSample
{
    public class Category
    {
        public int Id { get; set; }
        public string CategoryName { get; set; }
    }
}

注意 {get;设置;}的

最后一点,让很多事情变得简单的粘合剂是将所有数据放入模型并绑定到模型。这就是 WPF 的工作方式。

using System.Collections.Generic;
namespace WPFListBoxSample
{
    public class WPFListBoxModel
    {
        private IList<Category> _categories;
        public IList<Category> Categories
        {
            get
            {
                if (_categories == null)
                    _categories = new List<Category>();
                return _categories; }
            set { _categories = value; }
        }
    }
}

【讨论】:

    【解决方案2】:

    我会尝试这样的:

    var myConnection = new SqlConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "ProgramsList.sdf");
    var cmd = new SqlCommand("SELECT Name FROM CategoryList ORDER BY Name DESC", myConnection);
    
    myConnection.Open();
    CategoryList.Items.Clear();
    
    var sda = new SqlDataAdapter(cmd);
    var ds = new DataSet();
    sda.Fill(ds);
    
    CategoryList.ItemsSource = ds.Tables["CategoryList"];
    
    myConnection.Close(); 
    

    请注意,您需要在 CategoryList 对象中设置正确的绑定,可能通过一些 XAML,如下所示:

    <ListBox>
        <ListBox.Resources>
            <DataTemplate x:Key="DataTemplateItem">
                <Grid Height="Auto" Width="Auto">
                    <TextBlock x:Name="Name" Text="{Binding Name}" />
                </Grid>
            </DataTemplate>
        </ListBox.Resources>
    </ListBox>
    

    【讨论】:

    • 我试过了,它在 ds.Tables["CategoryList"] 下给了我一个错误。我相信您可能混淆了数据表和集合。编辑:应该是 ds.Table["CategoryList"].AsEnumerable()。我会回复看看它是否有效。
    • 对不起。无论我做什么,它仍然崩溃并给我一个错误 26,即:错误定位服务器/指定的实例。有什么帮助吗? PS:再一次,应该是“ds.Tables[0].AsEnumerable();” :)
    • 实际上,ds.Tables 不需要 .AsEnumerable() 因为“.Tables”是用于数据集的,对吧?为什么 Visual Studio 要求进行这种转换?
    • 听起来你的问题出在连接字符串上?您确定计算出的路径正确吗?
    • 我希望如此。可以肯定的是,您可以通过在数据库资源管理器中选择 sdf 并查看连接字符串属性来访问连接字符串,对吗?编辑: Connection String 属性仅包含基本字符串;您还有其他建议添加的参数吗?
    【解决方案3】:

    也许你的意思是: ....

    CategoryList.Items.Add(dr.GetString(0));
    

    ....

    【讨论】:

      猜你喜欢
      • 2019-06-05
      • 1970-01-01
      • 2013-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多