使用 SQL (SDF) 数据库中的项目填充 WPF 列表框

发布于 2024-09-16 10:17:30 字数 794 浏览 10 评论 0原文

我已经搜索了很长一段时间如何做到这一点,但我还没有得到关于这个主题的直接答案,所以希望你们中的一位 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();

谁能帮助我吗?提前致谢!

I have been searching on how to do this for a very long time, and I have not managed to get a straight answer on the subject, so hopefully one of you StackOverflow users will be able to help me here. I have a WPF ListBox named CategoryList and a SDF database called ProgramsList.sdf (with two tables called CategoryList and ProgramsList). What I wish my program to do is get the category names from the CategoryList table and list them in the ListBox control called CategoryList.

Here's the code that I tried, but it only caused my program to crash.

    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();

Can anyone help me? Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

沉溺在你眼里的海 2024-09-23 10:17:30

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

这是您的主要 XAML 代码。请注意,按钮的单击方法将显示组合框当前选定的值。这将使以后的事情变得容易。希望这不是矫枉过正,但它展示了一些使 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; }
        }
    }
}

A much better way is to bind your list to an object you create. That way you can specify properties for DisplayMemberPath (what you see) and SelectedValuePath (your programs internal value).

Here is your main XAML code. Note than the click method of the button will display the currently selected value of the ComboBox. That is going to make things easy later on. Hopefully this is not overkill but it shows a few principles that make WPF easy.

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");
    }
}

}

The 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>

Your own object for representing a Category

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

Note the {get; set;}'s

Finally a little bit of glue that makes a lot of things easy is putting all your data in a model and binding to the model. This is the way to work 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; }
        }
    }
}
与他有关 2024-09-23 10:17:30

我会尝试这样的操作:

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>

I'd try something like this:

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(); 

Note, that you will need to setup the correct bindings in your CategoryList object, likely via some XAML like this:

<ListBox>
    <ListBox.Resources>
        <DataTemplate x:Key="DataTemplateItem">
            <Grid Height="Auto" Width="Auto">
                <TextBlock x:Name="Name" Text="{Binding Name}" />
            </Grid>
        </DataTemplate>
    </ListBox.Resources>
</ListBox>
够运 2024-09-23 10:17:30

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

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

Perhaps you mean:
....

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

....

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文