2010-08-24 62 views
3

我一直在尋找如何在很長一段時間內完成此任務,而且我還沒有設法就此問題獲得直接答案,所以希望你們中的一個人StackOverflow用戶將能夠在這裏幫助我。我有一個名爲CategoryList的WPF ListBox和一個名爲ProgramsList.sdf的SDF數據庫(帶有兩個名爲CategoryList和ProgramsList的表)。我希望我的程序要做的是從CategoryList表中獲取類別名稱,並將它們列在名爲CategoryList的ListBox控件中。使用SQL(SDF)數據庫中的項目填充WPF列表框

這是我嘗試過的代碼,但它只會導致我的程序崩潰。

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

任何人都可以幫助我嗎?提前致謝!

+0

我終於找到了答案,和男孩,是我笨!我在我的後臺代碼中使用SQL Server,這是一個聯網客戶端 - 服務器應用程序的框架,當時我應該使用SQL Compact Edition作爲本地桌面程序!我沒有意識到的是MDF適用於SQL Server,SDF適用於MDF。無論如何,我將Nate和Stratton的代碼結合起來,並將它們修改爲與SQL CE一起使用。感謝大家的幫助! – 2010-08-25 03:23:58

+0

在這裏,如果你需要加載字符串值意味着你需要把'dr.GetString(1)'。要麼你需要加載int值意味着你需要把'dr.GetInt32(0)'。它爲我工作。 [Check Here !!](https://stackoverflow.com/questions/38032750/error-unable-to-cast-object-of-type-system-int32-to-type-system-string/44644672#44644672) – User6667769 2017-06-20 10:32:03

回答

1

我想嘗試這樣的事:

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這樣的需要設置正確的綁定在你的所屬分類的對象,有可能:

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

我試過了,它在ds.Tables [「CategoryList」]下給了我一個錯誤。我相信你可能已經混淆了數據表和集合。 編輯:它應該是ds.Table [「CategoryList」]。AsEnumerable()。我會回覆看看它是否有效。 – 2010-08-24 17:46:00

+0

試試'ds.Tables [0];' – Nate 2010-08-24 17:49:48

+0

抱歉。無論我做什麼,它仍然崩潰,並給我一個錯誤26,這是:錯誤定位服務器/實例指定。任何幫助? PS:再一次,這應該是「ds.Tables [0] .AsEnumerable();」 :) – 2010-08-24 18:07:51

1

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

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

....

2

更好的方法是將您的列表綁定到您創建的對象。這樣你可以爲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; } 
     } 
    } 
} 
0

通常最好的方式連接到數據庫,使用WPF時,鏈接到的sql

相關問題