5

私はこれを行う方法を非常に長い間探してきましたが、この件について明確な答えを得ることができなかったので、StackOverflow ユーザーの 1 人がここで私を助けてくれることを願っています。CategoryList という名前の WPF ListBox と、ProgramsList.sdf という名前の SDF データベースがあります (CategoryList と ProgramsList という名前の 2 つのテーブルがあります)。プログラムで実行したいのは、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();

誰でも私を助けることができますか?前もって感謝します!

4

3 に答える 3

3

より良い方法は、作成したオブジェクトにリストをバインドすることです。このようにして、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; }
        }
    }
}
于 2010-08-24T20:07:40.450 に答える
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(); 

次のような XAML を介して、CategoryList オブジェクトに正しいバインディングを設定する必要があることに注意してください。

<ListBox>
    <ListBox.Resources>
        <DataTemplate x:Key="DataTemplateItem">
            <Grid Height="Auto" Width="Auto">
                <TextBlock x:Name="Name" Text="{Binding Name}" />
            </Grid>
        </DataTemplate>
    </ListBox.Resources>
</ListBox>
于 2010-08-24T17:09:48.127 に答える
1

おそらくあなたは次のことを意味します: ....

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

....

于 2010-08-24T17:17:07.750 に答える