Filling a WPF List with SQL Database Items (SDF)

I searched for how to do this for a very long time, and I was not able to get a direct answer on this topic, so I hope one of you StackOverflow users can help me. I have a ListBox WPF named CategoryList and an SDF database called ProgramsList.sdf (with two tables called CategoryList and ProgramList). What I want my program to do is get the category names from the CategoryList table and list them in a ListBox control called CategoryList.

Here is the code 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!

+3
4

. , 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>
+1

Perhaps you mean: ....

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

....

+1
source

Generally, the best way to connect to the database when using WPF is to reference sql

0
source

Source: https://habr.com/ru/post/1761355/


All Articles